Ping Ping - 9 months ago 77
AngularJS Question

Highlighting a filtered result in AngularJS

I'm using a ng-repeat and filter in angularJS like the phones tutorial but I'd like to highlight the search results in the page. With basic jQuery I would have simply parsed the page on key up on the input, but I'm trying to do it the angular way. Any ideas ?

My code :

<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>

Answer Source

In did that for AngularJS v1.2+


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


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


.highlightedText {
    background: yellow;