突出显示AngularJS中的筛选结果

时间:2013-03-20 09:30:45

标签: angularjs angularjs-ng-repeat

我正在使用ng-repeat和angularJS过滤器,如手机教程,但我想在页面中突出显示搜索结果。使用基本的jQuery,我只需要在输入上的键上解析页面,但我正在尝试以角度方式进行。有什么想法吗?

我的代码:

<input id="search" type="text" placeholder="Recherche DCI" ng-model="search_query" autofocus>
<tr ng-repeat="dci in dcis | filter:search_query">
            <td class='marque'>{{dci.marque}} ®</td>
            <td class="dci">{{dci.dci}}</td>
 </tr>

13 个答案:

答案 0 :(得分:88)

用于AngularJS v1.2 +

HTML:     

<span ng-bind-html="highlight(textToSearchThrough, searchText)"></span>

JS:

$scope.highlight = function(text, search) {
    if (!search) {
        return $sce.trustAsHtml(text);
    }
    return $sce.trustAsHtml(text.replace(new RegExp(search, 'gi'), '<span class="highlightedText">$&</span>'));
};

CSS:

.highlightedText {
    background: yellow;
}

答案 1 :(得分:22)

angular ui-utils仅支持一个术语。我使用以下过滤器而不是范围函数:

app.filter('highlight', function($sce) {
  return function(str, termsToHighlight) {
    // Sort terms by length
    termsToHighlight.sort(function(a, b) {
      return b.length - a.length;
    });
    // Regex to simultaneously replace terms
    var regex = new RegExp('(' + termsToHighlight.join('|') + ')', 'g');
    return $sce.trustAsHtml(str.replace(regex, '<span class="match">$&</span>'));
  };
});

HTML:

<span ng-bind-html="theText | highlight:theTerms"></span>

答案 2 :(得分:13)

尝试Angular UI

过滤器 - &gt; Highlite(过滤器)。 还有Keypress指令。

答案 3 :(得分:8)

的index.html

<!DOCTYPE html>
<html>
  <head>
    <script src="angular.js"></script>
    <script src="app.js"></script>
    <style>
      .highlighted { background: yellow }
    </style>
  </head>

  <body ng-app="Demo">
    <h1>Highlight text using AngularJS.</h1>

    <div class="container" ng-controller="Demo">
      <input type="text" placeholder="Search" ng-model="search.text">

      <ul>
        <!-- filter code -->
        <div ng-repeat="item in data | filter:search.text"
           ng-bind-html="item.text | highlight:search.text">
        </div>
      </ul>
    </div>
  </body>
</html>

app.js

angular.module('Demo', [])
  .controller('Demo', function($scope) {
    $scope.data = [
      { text: "<< ==== Put text to Search ===== >>" }
    ]
  })
  .filter('highlight', function($sce) {
    return function(text, phrase) {
      if (phrase) text = text.replace(new RegExp('('+phrase+')', 'gi'),
        '<span class="highlighted">$1</span>')

      return $sce.trustAsHtml(text)
    }
  })

参考:http://codeforgeek.com/2014/12/highlight-search-result-angular-filter/ 演示:http://demo.codeforgeek.com/highlight-angular/

答案 4 :(得分:5)

angular-bootstraptypeaheadHighlight

中有标准的突出显示过滤器

用法

<span ng-bind-html="text | typeaheadHighlight:query"></span>

范围{text:"Hello world", query:"world"}呈现

<span...>Hello <strong>world</strong></span>

答案 5 :(得分:5)

我希望我的光照例能让人们更容易理解:

  app.filter('highlight', function() {
    return function(text, phrase) {
      return phrase 
        ? text.replace(new RegExp('('+phrase+')', 'gi'), '<kbd>$1</kbd>') 
        : text;
    };
  });
  <input type="text" ng-model="search.$">

  <ul>
    <li ng-repeat="item in items | filter:search">
      <div ng-bind-html="item | highlight:search.$"></div>
    </li>
  </ul>

enter image description here

答案 6 :(得分:4)

在这个帖子中关闭@ uri的答案,我将其修改为使用单个字符串 OR 一个字符串数组。

这是 TypeScript 版本

module myApp.Filters.Highlight {
    "use strict";

    class HighlightFilter {
        //This will wrap matching search terms with an element to visually highlight strings
        //Usage: {{fullString | highlight:'partial string'}}
        //Usage: {{fullString | highlight:['partial', 'string, 'example']}}

        static $inject = ["$sce"];

        constructor($sce: angular.ISCEService) {

            // The `terms` could be a string, or an array of strings, so we have to use the `any` type here
            /* tslint:disable: no-any */
            return (str: string, terms: any) => {
                /* tslint:enable */

                if (terms) {
                    let allTermsRegexStr: string;

                    if (typeof terms === "string") {
                        allTermsRegexStr = terms;
                    } else { //assume a string array
                        // Sort array by length then  join with regex pipe separator
                        allTermsRegexStr = terms.sort((a: string, b: string) => b.length - a.length).join('|');
                    }

                //Escape characters that have meaning in regular expressions
                //via: http://stackoverflow.com/a/6969486/79677
                allTermsRegexStr = allTermsRegexStr.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");

                    // Regex to simultaneously replace terms - case insensitive!
                    var regex = new RegExp('(' + allTermsRegexStr + ')', 'ig');

                    return $sce.trustAsHtml(str.replace(regex, '<mark class="highlight">$&</mark>'));
                } else {
                    return str;
                }
            };
        }
    }

    angular
        .module("myApp")
        .filter("highlight", HighlightFilter);
};

JavaScript

中转换为此内容
var myApp;
(function (myApp) {
    var Filters;
    (function (Filters) {
        var Highlight;
        (function (Highlight) {
            "use strict";
            var HighlightFilter = (function () {
                function HighlightFilter($sce) {
                    // The `terms` could be a string, or an array of strings, so we have to use the `any` type here
                    /* tslint:disable: no-any */
                    return function (str, terms) {
                        /* tslint:enable */
                        if (terms) {
                            var allTermsRegexStr;
                            if (typeof terms === "string") {
                                allTermsRegexStr = terms;
                            }
                            else {
                                // Sort array by length then  join with regex pipe separator
                                allTermsRegexStr = terms.sort(function (a, b) { return b.length - a.length; }).join('|');
                            }

                            //Escape characters that have meaning in regular expressions
                            //via: http://stackoverflow.com/a/6969486/79677
                            allTermsRegexStr = allTermsRegexStr.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");

                            // Regex to simultaneously replace terms - case insensitive!
                            var regex = new RegExp('(' + allTermsRegexStr + ')', 'ig');
                            return $sce.trustAsHtml(str.replace(regex, '<mark class="highlight">$&</mark>'));
                        }
                        else {
                            return str;
                        }
                    };
                }
                //This will wrap matching search terms with an element to visually highlight strings
                //Usage: {{fullString | highlight:'partial string'}}
                //Usage: {{fullString | highlight:['partial', 'string, 'example']}}
                HighlightFilter.$inject = ["$sce"];
                return HighlightFilter;
            })();
            angular.module("myApp").filter("highlight", HighlightFilter);
        })(Highlight = Filters.Highlight || (Filters.Highlight = {}));
    })(Filters = myApp.Filters || (myApp.Filters = {}));
})(myApp|| (myApp= {}));
;

或者,如果您只想要一个简单的JavaScript实现,而不使用那些生成的命名空间:

app.filter('highlight', ['$sce', function($sce) {
    return function (str, terms) {
        if (terms) {
            var allTermsRegexStr;
            if (typeof terms === "string") {
                allTermsRegexStr = terms;
            }
            else {
                // Sort array by length then  join with regex pipe separator
                allTermsRegexStr = terms.sort(function (a, b) { return b.length - a.length; }).join('|');
            }

            //Escape characters that have meaning in regular expressions
            //via: http://stackoverflow.com/a/6969486/79677
            allTermsRegexStr = allTermsRegexStr.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");

            // Regex to simultaneously replace terms - case insensitive!
            var regex = new RegExp('(' + allTermsRegexStr + ')', 'ig');
            return $sce.trustAsHtml(str.replace(regex, '<mark class="highlight">$&</mark>'));
        }
        else {
            return str;
        }
    };
}]);

已编辑以包含之前已解决此问题的修复程序是搜索.的人或在正则表达式中有意义的任何其他字符。现在,这些角色首先被转义。

答案 7 :(得分:1)

使用当搜索词与元素包含的数据相关时应用的ng-class。

所以在你重复的元素上,你有ng-class="{ className: search_query==elementRelatedValue}"

在满足条件时动态地将类“className”应用于元素。

答案 8 :(得分:0)

关于特殊问题的问题,我认为只是逃避你可能会失去正则表达式搜索。

这个怎么样:

function(text, search) {
    if (!search || (search && search.length < 3)) {
        return $sce.trustAsHtml(text);
    }

    regexp  = '';

    try {
        regexp = new RegExp(search, 'gi');
    } catch(e) {
        return $sce.trustAsHtml(text);
    }

    return $sce.trustAsHtml(text.replace(regexp, '<span class="highlight">$&</span>'));
};

无效的正则表达式可能只是键入文本的用户:

  • 有效:m
  • 无效:m [
  • 无效:m [ô
  • 无效:m [ôo
  • 有效:m [ôo]
  • 有效:m [ôo] n
  • 有效:m [ôo] ni
  • 有效:m [ôo] nic
  • 有效:m [ôo] nica

你觉得@Mik Cox怎么样?

答案 9 :(得分:0)

另一个主张:

app.filter('wrapText', wrapText);

function wrapText($sce) {
    return function (source, needle, wrap) {
        var regex;

        if (typeof needle === 'string') {
            regex = new RegExp(needle, "gi");
        } else {
            regex = needle;
        }

        if (source.match(regex)) {
            source = source.replace(regex, function (match) {
                return $('<i></i>').append($(wrap).text(match)).html();
            });
        }

        return $sce.trustAsHtml(source);
    };
} // wrapText

wrapText.$inject = ['$sce'];

// use like this
$filter('wrapText')('This is a word, really!', 'word', '<span class="highlight"></span>');
// or like this
{{ 'This is a word, really!' | wrapText:'word':'<span class="highlight"></span>' }}

我接受批评! ; - )

答案 10 :(得分:0)

感谢您提出这个问题,因为这也是我正在处理的问题。

但有两件事:

首先,最佳答案很棒但是对它的评论是准确的,highlight()有特殊字符的问题。该评论建议使用一个可以工作的转义链,但他们建议使用正在逐步淘汰的unescape()。我最终得到了什么:

$sce.trustAsHtml(decodeURI(escape(text).replace(new RegExp(escape(search), 'gi'), '<span class="highlightedText">$&</span>')));

其次,我试图在URL的数据绑定列表中执行此操作。在highlight()字符串中,您不需要数据绑定。

示例:

<li>{{item.headers.host}}{{item.url}}</li>

变成了:

<span ng-bind-html="highlight(item.headers.host+item.url, item.match)"></span>

将问题留在{{}}并遇到各种错误时遇到了问题。

希望这有助于任何人遇到同样的问题。

答案 11 :(得分:0)

如果您使用的是角度材质库,则会有一个名为md-highlight-text

的内置指令

来自文档:

<input placeholder="Enter a search term..." ng-model="searchTerm" type="text">
<ul>
  <li ng-repeat="result in results" md-highlight-text="searchTerm">
    {{result.text}}
  </li>
</ul>

链接到文档:https://material.angularjs.org/latest/api/directive/mdHighlightText

答案 12 :(得分:0)

我的高亮解决方案将其与angular-ui-tree元素一起使用:https://codepen.io/shnigi/pen/jKeaYG

angular.module('myApp').filter('highlightFilter', $sce =>
 function (element, searchInput) {
   element = element.replace(new RegExp(`(${searchInput})`, 'gi'),
             '<span class="highlighted">$&</span>');
   return $sce.trustAsHtml(element);
 });

添加CSS:

.highlighted {
  color: orange;
}

HTML:

<p ng-repeat="person in persons | filter:search.value">
  <span ng-bind-html="person | highlightFilter:search.value"></span>
</p>

并添加搜索输入:

<input type="search" ng-model="search.value">