javascript 如何在 AngularJS 中有条件地用标签包围文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16579597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to surround text with tag conditionally in AngularJS?
提问by aztack
How to surround text with tag conditionally in AngularJS? for example:
如何在 AngularJS 中有条件地用标签包围文本?例如:
function Controller($scope){
$scope.showLink = true or false, retrieved from server;
$scope.text = "hello";
$scope.link = "..."
}
if {{showLink}} is false
如果 {{showLink}} 为假
<div>hello</div>
else
别的
<div><a href="{{link}}">hello</a></div>
回答by Umur Kontac?
回答by Casey
As far as I can tell there's no out-of-the-box feature to do this. I wasn't really satisfied with the other answers because they still require you to repeat the inner contents in your view.
据我所知,没有现成的功能可以做到这一点。我对其他答案并不满意,因为它们仍然要求您在您的视图中重复内部内容。
Well, you can fix this with your own directive.
好吧,你可以用你自己的指令来解决这个问题。
app.directive('myWrapIf', [
function()
{
return {
restrict: 'A',
transclude: false,
compile:
{
pre: function(scope, el, attrs)
{
if (!attrs.wrapIf())
{
el.replaceWith(el.html());
}
}
}
}
}
]);
Usage:
用法:
<a href="/" data-my-wrap-if="list.indexOf(currentItem) %2 === 0">Some text</a>
"Some text" will be a link only if the condition is met.
“某些文本”只有在满足条件时才会成为链接。
回答by Arun P Johny
Try
尝试
<div ng-show="!link">hello</div>
<div ng-show="!!link"><a href="{{link}}">hello</a></div>
回答by NilsH
回答by Qualtagh
Modified version of Casey's answer to support AngularJS expressions:
Casey 的答案的修改版本以支持 AngularJS 表达式:
app.directive('removeTagIf', ['$interpolate', function($interpolate) {
return {
restrict: 'A',
link: function(scope, el, attrs) {
if (scope.$eval(attrs.removeTagIf))
el.replaceWith($interpolate(el.html())(scope));
}
};
}]);
Usage:
用法:
<a href="/" remove-tag-if="$last">{{user}}'s articles</a>