亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

angularjs實(shí)現(xiàn)搜索的關(guān)鍵字在正文中高亮出來

 更新時間:2017年06月13日 10:43:33   作者:灰太大  
這篇文章主要介紹了angularjs實(shí)現(xiàn)搜索的關(guān)鍵字在正文中高亮出來,具有一定的參考價值,感興趣的小伙伴們可以參考一下

1、定義高亮 filter

我們希望搜索的關(guān)鍵字在正文中高亮出來,正文內(nèi)容就是過濾器的第一個參數(shù),第二個參數(shù)就是搜索關(guān)鍵字,這樣,我們的過濾器將會有兩個參數(shù)了。

高亮的原理很簡單,將需要高亮的內(nèi)容使用 span 標(biāo)記隔離出來,再加上一個高亮的 class樣式 進(jìn)行描述就可以了。

app.filter("highlight", function($sce, $log){
  var fn = function(text, search){
    $log.info("text: " + text);
    $log.info("search: " + search);
    if (!search) {
      return $sce.trustAsHtml(text);
    }
    text = encodeURIComponent(text);
    search = encodeURIComponent(search);
    var regex = new RegExp(search, 'gi')
    var result = text.replace(regex, '<span class="highlightedTextStyle">$&</span>');
    result = decodeURIComponent(result);
    $log.info("result: " + result );
    return $sce.trustAsHtml(result);
  };
  return fn;
});

$sce, 和 $log 是 angular 提供的兩個服務(wù),其中 $sce 服務(wù)需要使用 ngSanitize 模塊。關(guān)于這個模塊,可以參考:angular-ngSanitize模塊-$sanitize服務(wù)詳解

2、定義html視圖

<div ng-controller="search">
      <div>
        <input type="text" ng-model="notify.search" value=""/>
      </div>
      <!--text內(nèi)容會高亮顯示搜索關(guān)鍵字-->
      <div ng-bind-html="text | highlight:notify.search">
      </div>
</div>

3、控制器

app.controller("search", function($scope){
  $scope.text = "hello, world. hello, world. hello, world. this is filter example.";
  $scope.notify.search = "";
})

注意在控制器中引入過濾器highlight

當(dāng)搜索的關(guān)鍵字為數(shù)字時,如"1",報(bào)如下錯誤:(輸入漢字時沒有問題)


一些解決辦法:

1.直接try catch處理,這樣太簡單了,并且會導(dǎo)致新的問題出現(xiàn)

2.把escape全部改成encodeURIComponent編碼,試了一下不能解決問題

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論