Highlighting a filtered result in AngularJS

前端 未结 13 2088
醉话见心
醉话见心 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:34

    angular ui-utils supports only one term. I'm using the following filter rather than a scope function:

    app.filter('highlight', function($sce) {
      return function(str, termsToHighlight) {
        // Sort terms by length
        termsToHighlight.sort(function(a, b) {
          return b.length - a.length;
        });
        // Regex to simultaneously replace terms
        var regex = new RegExp('(' + termsToHighlight.join('|') + ')', 'g');
        return $sce.trustAsHtml(str.replace(regex, '$&'));
      };
    });
    

    And the HTML:

    
    

提交回复
热议问题