Highlighting a filtered result in AngularJS

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

    Another proposition:

    app.filter('wrapText', wrapText);
    
    function wrapText($sce) {
        return function (source, needle, wrap) {
            var regex;
    
            if (typeof needle === 'string') {
                regex = new RegExp(needle, "gi");
            } else {
                regex = needle;
            }
    
            if (source.match(regex)) {
                source = source.replace(regex, function (match) {
                    return $('').append($(wrap).text(match)).html();
                });
            }
    
            return $sce.trustAsHtml(source);
        };
    } // wrapText
    
    wrapText.$inject = ['$sce'];
    
    // use like this
    $filter('wrapText')('This is a word, really!', 'word', '');
    // or like this
    {{ 'This is a word, really!' | wrapText:'word':'' }}
    

    I'm open to criticism ! ;-)

提交回复
热议问题