Highlighting a filtered result in AngularJS

前端 未结 13 2059
醉话见心
醉话见心 2020-12-01 00:12

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 pars

相关标签:
13条回答
  • 2020-12-01 00:36

    Thanks for asking this as it was something I was dealing with as well.

    Two things though:

    First, The top answer is great but the comment on it is accurate that highlight() has problem with special characters. That comment suggests using an escaping chain which will work but they suggest using unescape() which is being phased out. What I ended up with:

    $sce.trustAsHtml(decodeURI(escape(text).replace(new RegExp(escape(search), 'gi'), '<span class="highlightedText">$&</span>')));
    

    Second, I was trying to do this in a data bound list of URLs. While in the highlight() string, you don't need to data bind.

    Example:

    <li>{{item.headers.host}}{{item.url}}</li>
    

    Became:

    <span ng-bind-html="highlight(item.headers.host+item.url, item.match)"></span>
    

    Was running into problems with leaving them in {{ }} and getting all sorts of errors.

    Hope this helps anybody running into the same problems.

    0 讨论(0)
提交回复
热议问题