如何使用AngularJS过滤器跳过字符串中的图像选项卡?

问题描述 投票:1回答:1

我想在过滤时跳过img标签。我已经测试但是不行。它仍然可以过滤img或src值。所以请帮助我。

这是我的代码

过滤

app.filter('highlight', function ($sce) {
    return function (text, phrase) {
        if (phrase) {
            var matches = String(text).match(/<img.*?src="([^"]*)"[^>]*>(?:<\/img>)?/m);
            var img_src = (matches && matches.length && matches[0]) ? matches[0] : '';
            text = text.replace(img_src, "#");

            text = text.replace(new RegExp('(' + phrase + ')', 'ig'),
                '<span class="highlighted">$1</span>');
            text = text.replace("#", img_src);
        }
        return $sce.trustAsHtml(text)
    }
})

调节器

$scope.imgList = [];
        imgList.push('<img src="image1.jpg">');
        imgList.push('<img src="image2.jpg">');
        imgList.push('Using <img src="image1.jpg">“this” instead of “scope” <img src="image3.jpg"/> <p>Post Description <img src="image4.jpg"/></p>');

HTML

<input ng-model="searchText" type="text">

<ul>
    <li ng-repeat="img in imgList">
        <p ng-bind-html="img | highlight:searchText"></p>
    </li>
</ul>
html css angularjs
1个回答
0
投票

我得到了答案。过滤器如下:

app.filter('highlight', function ($sce) {
    return function (text, phrase) {
        if (text && phrase) {
            var matches = String(text).match(/<img.*?src="([^"]*)"[^>]*>(?:<\/img>)?/g);
            if(matches && matches.length != 0){
                for(var i = 0; i < matches.length; i++) {
                    text = text.replace(matches[i], "#_#" + i);
                }
            }

            text = text.replace(new RegExp('(' + phrase + ')', 'ig'), '<span class="highlighted">$1</span>');
            if(matches && matches.length != 0){
                for(var i = 0; i < matches.length; i++) {
                    text = text.replace("#_#" + i, matches[i]);
                }
            }
        }

        return $sce.trustAsHtml(text)
    }
})
© www.soinside.com 2019 - 2024. All rights reserved.