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

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

高亮的原理很簡(jiǎn)單,將需要高亮的內(nèi)容使用 span 標(biāo)記隔離出來(lái),再加上一個(gè)高亮的 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 提供的兩個(gè)服務(wù),其中 $sce 服務(wù)需要使用 ngSanitize 模塊。關(guān)于這個(gè)模塊,可以參考:angular-ngSanitize模塊-$sanitize服務(wù)詳解

2、定義html視圖

<div ng-controller="search">
            <div>
                <input type="text" ng-model="notify.search" value=""/>
            </div>
            <!--text內(nèi)容會(huì)高亮顯示搜索關(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 = "";
})

注意在控制器中引入過(guò)濾器highlight

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

QQ截圖20170612154133.png

一些解決辦法:
1.直接try catch處理,這樣太簡(jiǎn)單了,并且會(huì)導(dǎo)致新的問(wèn)題出現(xiàn)
2.把escape全部改成encodeURIComponent編碼,試了一下不能解決問(wèn)題

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容