【问题标题】:AngularJS highlight search no resultAngularJS高亮搜索无结果
【发布时间】: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


    【解决方案1】:

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

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

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

    太笼统了,但希望对你有帮助:)

    【讨论】:

    • 嘿,你能在我的脚本和 HTML 中给我一个例子吗?抱歉,我对 Angular 很陌生!
    猜你喜欢
    • 2015-07-08
    • 2012-01-21
    • 1970-01-01
    • 2017-03-03
    • 2015-10-21
    • 1970-01-01
    • 2012-11-27
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多