我之前在过滤评论输入时遇到过类似的情况。我有 4 个不同的过滤器,当用户单击提交时,它将运行一个函数,该函数将在评论副本上运行所有 4 个过滤器。把我的过滤器扔在那里以防万一。警告:确保将 $filter 注入控制器,我讨厌忘记注入东西。这是代码:
注入:
.controller('Controller', function ($scope, $filter){
//CODE GOES HERE
});
HTML:
<ul ng-repeat="comment in comments">
<li>{{comment.user_name}}</li>
<li dynamic="deliberatelyTrustDangerousSnippet(comment.comment_copy)"></li>
</ul>
控制器:
$scope.deliberatelyTrustDangerousSnippet = function(comment) {
comment = $filter('breaks')(comment);
comment = $filter('links')(comment);
comment = $filter('images')(comment);
comment = $filter('youtubeLinks')(comment);
return comment;
};
过滤器:
.filter('breaks', function () {
return function (text) {
if (text !== undefined) return text.replace(/ /g, '<br />');
};
})
.filter('links', function () {
return function (text) {
if (text !== undefined){
return text.replace(/(?:http:\/\/)?(?:www\.)?((?:[\w-\.]*)(?:\.(?:com|net|org|co|be))(?:(?:[\/?\w?=?&?(?:&)?\.?-]*)))/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|-)*)(?:(?:&feature=related)?)))(?:")(?:.*(?:<\/a>))/g, '<youtube id="$1"></youtube>');
}
};
})