Highlight search result using angular.js and ui.utils

Problem

I am trying to add some highlighting of a search result using angular. I have found that the Highlight functionality in UI.Utils gives the result I would like. But the examples are all using ng-bind-html-unsafe. Is there a way of using this template approach instead?

<div ng-app>
    <div ng-controller="searchController">
        <input ng-model="query"/>

        <div class="t">
            <div class="tr" ng-repeat="person in result">
                <div class="td">{{person.FirstName | highlight}}</div>
                <div class="td">{{person.LastName | highlight}}</div>
            </div>
        </div>    
    </div>
</div>

Check here for code on jsfiddle: http://jsfiddle.net/vs7Dm/4/

Problem courtesy of: thomas

Solution

To do this you must have to complete a few steps before using the highlight filter from ui-angular

You need to have ngSanitize as a dependency. see below;

var app = angular.module('app',['ngSanitize']);

Add this to your HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-sanitize.min.js"/>

Copy the highlight filter to your app like so

    app.filter('highlight', function () {
    return function (text, search, caseSensitive) {
        if (text && (search || angular.isNumber(search))) {
            text = text.toString();
            search = search.toString();
            if (caseSensitive) {
                return text.split(search).join('<span class="ui-match">' + search + '</span>');
            } else {
                return text.replace(new RegExp(search, 'gi'), '<span class="ui-match">$&</span>');
            }
        } else {
            return text;
        }
    };
});

Then what you do is for your searchable results section:

<input type="text" placeholder="Search..." ng-model="searchText" />
<div ng-repeat="address in addresses | filter:searchText">
   <p ng-bind-html="address.title | highlight:searchText"></p>
   <p ng-bind-html="address.address_1 | highlight:searchText"></p>
   <p ng-bind-html="address.address_2 | highlight:searchText"></p>
   <p ng-bind-html="address.address_3 | highlight:searchText"></p>
</div>

Notice that the use of ng-bind-html in the ng-repeat rather than the ng-bind-html-unsafe that ui-angular suggests. -html-unsafe was removed from the core and needs to be injected into your app.

This was everything I need to get this to run using AngularJS v1.3.0.

Let me know if you have any questions regarding this method.

Demo here

Solution courtesy of: Doug

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.