我正在使用 Angular JS 获取 ng-repeat
通过 Twitter 推文。我需要突出显示推文字符串的部分内容,例如 @tag
和#hash
,所以建议我使用 replace
在我想要突出显示的内容周围添加 DOM 包装器。
问题是,因为我没有直接输出到 DOM,而是 ng-repeating
在范围变量上,html 标签似乎没有添加到字符串中。
问题:如何将 html 标签附加到 JS 字符串?
<小时/>指令片段:
scope.getTweets = function () {
ModulesService.getTweets().success(function (res) {
if (res && Array.isArray(res)) {
scope.tweets = parseTweets(res);
}
});
};
scope.getTweets();
var parseTweets = function (tweets) {
tweets.forEach(function (tweet) {
tweet.text.replace(/(@[^ ]+)/g, '<a class="user">$1</a>').
replace(/(#[^ ]+)/g, '<span class="hash">$1</span>').
replace(/(https?:\/\/[^ ]+)/g, '<a href="$1">$1</a>');
console.log('tweet!', tweet.text); //does not contain altered HTML
});
return tweets;
};
HTML:
<div ng-repeat="tweet in tweets" class="post-body clearfix">
{{tweet.text}}
</div>
最佳答案
像这样使用过滤器
filterExample.filter('filterName', function () {
return function (text) {
var str = text.replace(/(@[^ ]+)/g, '<a class="user">$1</a>').
replace(/(#[^ ]+)/g, '<span class="hash">$1</span>').
replace(/(https?:\/\/[^ ]+)/g, '<a href="$1">$1</a>');
return str.toLowerCase();
};
})
和 html
<div ng-repeat="tweet in tweets" class="post-body clearfix">
<span ng-bind-html="tweet.text | filterName"></span>
</div>
关于javascript - 正则表达式替换指令中的 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35704715/