繁体   English   中英

AngularJS高亮显示搜索无结果

[英]AngularJS highlight search no result

我正在使用来自https://codeforgeek.com/2014/12/highlight-search-result-angular-filter/的AngularJS高亮搜索

问题是,如果我搜索关键字,突出显示效果会很完美。 但是,只要键入内容中不存在的关键字,它就会隐藏所有内容。 见下面的图片:

重点关键字: 重点关键字

关键字错误-没有显示内容: iincorrect关键字-未显示内容

这是我的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参数,该关键字不突出全部内容而是隐藏全部内容?

您可以将第二个div放入ng-if ,例如, ng-if=" $ctrl.search.text.found() === false" 您将需要在控制器中创建一个函数,如下所示:

let found = () => search.text.match('input.ref', 'words[].ref') ? true : false

因此,这将呈现其他内容,而不是隐藏所有内容。

它太通用了,但希望对您有所帮助:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM