Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

SearchExample

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

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

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

Can you help me?

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

Angular UI is a great choice. You can also do it with filter like: http://embed.plnkr.co/XbCsxmfrgmdtOAeBZPUp/preview

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">
</li>
share|improve this answer
add comment

Try Angular UI

They have a highlight directive. You can use it as a reference to make your own (or just use it directly).

share|improve this answer
    
There's no 'simple' way to do this in core angular... though you could argue it is 'simple' to write your own directive that does it. Either way, you need a custom directive that can search through its contents and dynamically create styled spans based on a match. I would also recommend using an existing one if possible, like Angular UI, to avoid some headache. –  Hylianpuffball Dec 15 '13 at 19:53
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.