angularjs实现搜索的关键字在正文中高亮出来

1、定义高亮 filter
我们希望搜索的关键字在正文中高亮出来,正文内容就是过滤器的第一个参数,第二个参数就是搜索关键字,这样,我们的过滤器将会有两个参数了。

高亮的原理很简单,将需要高亮的内容使用 span 标记隔离出来,再加上一个高亮的 class样式 进行描述就可以了。

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, '$&');
        result = decodeURIComponent(result);
        $log.info("result: " + result );
        return $sce.trustAsHtml(result);
    };

    return fn;
});

$sce, 和 $log 是 angular 提供的两个服务,其中 $sce 服务需要使用 ngSanitize 模块。关于这个模块,可以参考:angular-ngSanitize模块-$sanitize服务详解

2、定义html视图

3、控制器

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

注意在控制器中引入过滤器highlight

当搜索的关键字为数字时,如"1",报如下错误:(输入汉字时没有问题)

angularjs实现搜索的关键字在正文中高亮出来_第1张图片
QQ截图20170612154133.png

一些解决办法:
1.直接try catch处理,这样太简单了,并且会导致新的问题出现
2.把escape全部改成encodeURIComponent编码,试了一下不能解决问题

你可能感兴趣的:(angularjs实现搜索的关键字在正文中高亮出来)