[英]Highlight list of terms using AngularJS
I have a list of search results, each with a summary and a list of terms to highlight in that summary (but each summary has its own highlight terms and shouldn't be affected by the others). 我有一个搜索结果列表,每个搜索结果都有一个摘要和该摘要中要突出显示的术语列表(但每个摘要都有其自己的突出显示术语,不应受其他术语的影响)。
I am quite new to angularjs and having trouble getting this to work. 我对angularjs很陌生,无法正常工作。 This is my current html without the highlighting. 这是我当前的html,没有突出显示。
<ul ng-if="searchResults.length > 0">
<li ng-repeat="searchResult in searchResults">
<h2>{{ searchResult.Title }} </h2>
<p>{{ searchResult.Summary }}</p>
</li>
</ul>
This is an example of what one of the searchResult object's data looks like: 这是searchResult对象的数据之一的示例:
searchResult: {
"HighlightTerms": [ "text", "summary" ],
"Summary": "this is a text summary"
"Title": "my title"
}
So ideally the first result would display 'text' and 'summary' with a yellow highlight. 因此理想情况下,第一个结果将显示“文本”和“摘要”并带有黄色突出显示。
Any suggestions on the best way to do this? 关于最佳方法的任何建议吗? I have tried using ng-bind-html but couldnt get it to work 我尝试使用ng-bind-html,但无法正常工作
Here is an example of how it should look if there was one HighlightTerm - 'sensor'. 这是一个示例,说明如果有一个HighlightTerm-“传感器”,应该如何显示。
You can check angular ui-utils
highlight
feature 您可以检查角度ui-utils
highlight
功能
http://angular-ui.github.io/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>
Sorry for the late answer but this could help other people. 对不起,您回答的太晚了,但这可以帮助其他人。
You can create you own directive based on ui-utils: 您可以基于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;
};
});
Where MODULE_NAME is the name of your module. 其中MODULE_NAME是您的模块的名称。
Usage Example: 用法示例:
<p ng-bind-html="mymodel.text | highlightWords:searchTerms"></p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.