使用AngularJS突出显示术语列表

时间:2014-02-26 11:28:18

标签: javascript angularjs

我有一个搜索结果列表,每个搜索结果都有一个摘要和一个要在该摘要中突出显示的术语列表(但每个摘要都有自己的突出显示术语,不应受其他人的影响)。

我对angularjs很新,并且无法让它工作。 这是我目前的html没有突出显示。

<ul ng-if="searchResults.length > 0">
    <li ng-repeat="searchResult in searchResults">
        <h2>{{ searchResult.Title }} </h2>       
        <p>{{ searchResult.Summary }}</p>
    </li>
</ul>

这是searchResult对象的数据之一的示例:

searchResult:  { 
   "HighlightTerms": [ "text", "summary" ],
   "Summary": "this is a text summary"
   "Title": "my title"
} 

理想情况下,第一个结果会显示带有黄色突出显示的“文字”和“摘要”。

有关最佳方法的任何建议吗?我尝试过使用ng-bind-html但无法让它工作

以下是一个示例,看看是否有一个HighlightTerm - 'sensor'。

example

2 个答案:

答案 0 :(得分:0)

您可以检查有角度的ui-utils highlight功能

http://angular-ui.github.io/ui-utils/#/highlight

<label><input type="checkbox" ng-model="caseSensitive"> Case Sensitive?</label>
<input placeholder="Enter some text to highlight" value="you" ng-model="highlightText">
<p ng-bind-html-unsafe="'Hello there, how are you today? I\'m fine thank you.' | highlight:highlightText:caseSensitive"></p>

<style>
.ui-match { background: yellow; }
</style>

答案 1 :(得分:0)

对于迟到的回答感到抱歉,但这可以帮助其他人。

您可以根据ui-utils创建自己的指令:

/**
 * Highlight words
 */
angular.module('MODULE_NAME')
    .filter('highlightWords', function () {
      return function (text, search) {
        if (text && (search || angular.isNumber(search))) {
          text = text.toString();
          search = search.toString();

          angular.forEach(search.split(/\s+/), function(word) {
            // reject some words from the filtering
            if (['span', 'class', 'ui-match'].indexOf(word) < 0) {

                var pattern = new RegExp("\\b" + word + "\\b", "gi");
                text = text.replace(pattern, '<span class="ui-match">$&</span>');
            }
          });
        }
        return text;
      };
});

MODULE_NAME是您模块的名称。

用法示例:

<p ng-bind-html="mymodel.text | highlightWords:searchTerms"></p>