【发布时间】:2019-03-08 16:04:22
【问题描述】:
我正在使用来自的 AngularJS 高亮搜索 https://codeforgeek.com/2014/12/highlight-search-result-angular-filter/
问题是,如果我搜索关键字,突出显示效果非常完美。但是只要我输入内容中不存在的关键字,它就会隐藏所有内容。见下图:
突出显示的关键字:
关键字不正确 - 未显示内容:
这是我的 JS
var newsApp = angular.module("NewsApp",[]);
newsApp.controller("newsCtrl",function($scope){
$scope.posts = [
{
"id" : "1",
"title" : "CMS Newsletter - 2018-01-02",
"content" : ""TEST CONTENT - ORIGINAL CONTENT IS CONFIDENTIAL",
},
];
});
newsApp.filter('unsafe', function($sce) {
return function(val) {
return $sce.trustAsHtml(val);
};
});
newsApp.filter('highlight', function($sce) {
return function(text, phrase) {
if (phrase) text = text.replace(new RegExp('('+phrase+')', 'gi'),
'<span style="background: red;">$1</span>')
return $sce.trustAsHtml(text)
}
这是我的 HTML
<div class="newsletter-control-bar-left">
<input type="text" ng-model="search.text" placeholder="Search for Keywords" />
</div>
<div style="margin-top: 50px;">
<div class="newsletter-archive">
<ul class="nav nav-pills nav-stacked col-md-3 newsletter-side">
<li ng-repeat="post in posts"><a href="#{{post.id}}" data-toggle="tab">{{post.title}}</a></li>
</ul>
<div class="tab-content col-md-9">
<div class="tab-pane active" id="#">Navigate through the the Newsletter Archive!</div>
<div class="tab-pane" id="{{post.id}}" ng-repeat="post in posts | filter:search.text">
<div>
<p id="search_para" ng-bind-html="post.content | highlight:search.text">
</p>
</div>
</div>
</div>
</div>
如果找不到关键字,有人知道如何实现 else 参数,它不会突出显示任何内容而不是隐藏整个内容?
【问题讨论】:
标签: javascript angularjs search filter highlight