1、定义高亮 filter
我们希望搜索的关键字在正文中高亮出来,正文内容就是过滤器的第一个参数,第二个参数就是搜索关键字,这样,我们的过滤器将会有两个参数了。
高亮的原理很简单,将需要高亮的内容使用 span 标记隔离出来,再加上一个高亮的 class样式 进行描述就可以了。
rush:js;">
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 模块。关于这个模块,可以参考:
2、定义html视图
rush:xhtml;">
3、控制器
rush:js;">
app.controller("search",function($scope){
$scope.text = "hello,world. hello,world. this is filter example.";
$scope.notify.search = "";
})
注意在控制器中引入过滤器highlight
当搜索的关键字为数字时,如"1",报如下错误:(输入汉字时没有问题)
一些解决办法:
1.直接try catch处理,这样太简单了,并且会导致新的问题出现
2.把escape全部改成encodeURIComponent编码,试了一下不能解决问题
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。
原文地址:https://www.jb51.cc/js/38651.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。