[英]Highlight list of terms using 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-“傳感器”,應該如何顯示。
您可以檢查角度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>
對不起,您回答的太晚了,但這可以幫助其他人。
您可以基於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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.