Dor Cohen Dor Cohen - 9 months ago 49
AngularJS Question

mark search string dynamically using angular.js

How can I mark my search pattern dynamically in my html?



I'm using angular and my html looks like this:

<input type="text" ng-model="viewmodel.searchString"/>
<!--Moving over all phrases-->
<div ng-repeat="phrase in viewmodel.Phrases">

I want the string matching pattern will be mark on every change in search string.

Can you help me?


Angular UI is a great choice. You can also do it with filter like:

The essence is as commented by @Hylianpuffball, dynamically create styled 'span' tags for the matches.

.filter('highlight', function($sce) {
  return function(text, phrase) {
    if (phrase) text = text.replace(new RegExp('('+phrase+')', 'gi'),
      '<span class="highlighted">$1</span>')

    return $sce.trustAsHtml(text)

And use it like:

<li ng-repeat="item in data | filter:search.title"
    ng-bind-html="item.title | highlight:search.title">