如何从angular.js中的另一个过滤器调用一个过滤器

Nik*_*ita 38 javascript angularjs

我有一个过滤器,linkifyStuff,我想在其中使用另一个过滤器处理一些变量.我无法弄清楚从另一个过滤器调用一个过滤器的语法.

我知道滤波器链接 - 这不是我想要做的.我想将过滤器应用于linkifyStuff过滤器中的局部变量,而不是其输入或输出.

我希望下面会有类似的工作,但$ filter('filtername')显然不是正确的语法.

module.filter('sanitizeStuff', function() {
    // ...
})

module.filter('prettifyStuff', function() {
    // ...
})

module.filter('linkifyStuff', function($filter) {
    return function(text) {
        // ...
        // ...
        return $filter('sanitizeStuff')(foo) + ' whatever ' + $filter('prettifyStuff')(bar)
    }
})
Run Code Online (Sandbox Code Playgroud)

我可以为sanitizeStuff和sanitizeStuff编写一个简单的js函数,并从这些过滤器调用该函数,但这似乎是错误的.如何以角度方式做任何建议?

谢谢.

Kha*_* TO 70

linkifyStuff使用<filterName>Filter语法注入过滤器.像这样:

app.filter('linkifyStuff', function(sanitizeStuffFilter,prettifyStuffFilter) {
    return function(text) {

        return sanitizeStuffFilter(text) + ' whatever ' + prettifyStuffFilter(text);
    }
});
Run Code Online (Sandbox Code Playgroud)

DEMO


rjm*_*226 5

我之前在过滤评论输入时遇到过类似的情况。我有 4 个不同的过滤器,当用户单击“提交”时,它将运行一个函数,该函数将在评论副本上运行所有 4 个过滤器。为了更好的测量,把我的过滤器扔在那里。警告:确保将 $filter 注入控制器中,我讨厌忘记注入东西。这是代码:

注射:

.controller('Controller', function ($scope, $filter){
    //CODE GOES HERE
});
Run Code Online (Sandbox Code Playgroud)

HTML:

<ul ng-repeat="comment in comments">
    <li>{{comment.user_name}}</li>
    <li dynamic="deliberatelyTrustDangerousSnippet(comment.comment_copy)"></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

控制器:

$scope.deliberatelyTrustDangerousSnippet = function(comment) {
    comment = $filter('breaks')(comment);
    comment = $filter('links')(comment);
    comment = $filter('images')(comment);
    comment = $filter('youtubeLinks')(comment);
    return comment;

};
Run Code Online (Sandbox Code Playgroud)

过滤器:

.filter('breaks', function () {
    return function (text) {
        if (text !== undefined) return text.replace(/&#10;/g, '<br />');
    };
})
.filter('links', function () {
    return function (text) {
        if (text !== undefined){
            return text.replace(/(?:http:\/\/)?(?:www\.)?((?:[\w-\.]*)(?:\.(?:com|net|org|co|be))(?:(?:[\/?\w?=?&?(?:&amp;)?\.?-]*)))/g, '<a target="_blank" href="http://$1">$1</a>');
        }
    };
})
.filter('images', function () {
    return function (text) {
        if (text !== undefined){
            return text.replace(/(?:<.*=")(.*(?:(?:\.(?:jpg|JPG|png|PNG|gif|GIF|jpeg|JPEG))))(?:")(?:.*(?:<\/a>))/g, '<img src="$1"/>');
        }
    };
})
.filter('youtubeLinks', function () {
    return function (text) {
        if (text !== undefined){
            return text.replace(/(?:<.*=")(?:(?:(?:(?:http:\/\/)|(?:www\.)|(?:http:\/\/www\.))(?:(?:youtube\.com.*v=)|(?:youtu\.be\/))((?:\w|\d|-)*)(?:(?:&amp;feature=related)?)))(?:")(?:.*(?:<\/a>))/g, '<youtube id="$1"></youtube>');
        }
    };
})
Run Code Online (Sandbox Code Playgroud)