Highlight search result with angular.js and ui.utils

I am trying to add highlighting to a search result using angular. I found that the Highlight function in UI.Utils gives the result I would like. But all the examples use ng-bind-html-unsafe. Is there any way to use this templated approach?

<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 out the jsfiddle code here: http://jsfiddle.net/vs7Dm/4/

+4
source share
1 answer

To do this, you need to follow a few steps before using the selection filter from ui- angular

You should 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 selection filter into the application this way

    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;
        }
    };
});

:

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

, ng-bind-html ng-repeat, ng-bind-html-, ui- angular . -html-unsafe .

, , AngularJS v1.3.0.

, - .

+5

Source: https://habr.com/ru/post/1538007/


All Articles