Javascript 如何在AngularJS中有条件地用标记包围文本?
如何在AngularJS中有条件地用标记包围文本? 例如:Javascript 如何在AngularJS中有条件地用标记包围文本?,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,如何在AngularJS中有条件地用标记包围文本? 例如: function Controller($scope){ $scope.showLink = true or false, retrieved from server; $scope.text = "hello"; $scope.link = "..." } 如果{{showLink}}为false <div>hello</div> 你好 否则 试试看 你好 您可以使用该指令 <div
function Controller($scope){
$scope.showLink = true or false, retrieved from server;
$scope.text = "hello";
$scope.link = "..."
}
如果{{showLink}}为false
<div>hello</div>
你好
否则
试试看
你好
您可以使用该指令
<div ng-switch on="showLink">
<div ng-switch when="true">
<a ng-href="link">hello</a>
</div>
<div ng-switch when="false">
Hello
</div>
</div>
app.directive('myWrapIf', [
function()
{
return {
restrict: 'A',
transclude: false,
compile:
{
pre: function(scope, el, attrs)
{
if (!attrs.wrapIf())
{
el.replaceWith(el.html());
}
}
}
}
}
]);
你好
适用于以下情况:
<div ng-switch="!!link">
<a ng-href="{{link}}" ng-switch-when="true">linked</a>
<span ng-switch-when="false">notlinked</span>
</div>
未链接
据我所知,没有现成的功能可以做到这一点。我对其他答案并不满意,因为它们仍然要求你重复你观点中的内在内容
好吧,你可以用你自己的指令来解决这个问题
<div ng-switch on="showLink">
<div ng-switch when="true">
<a ng-href="link">hello</a>
</div>
<div ng-switch when="false">
Hello
</div>
</div>
app.directive('myWrapIf', [
function()
{
return {
restrict: 'A',
transclude: false,
compile:
{
pre: function(scope, el, attrs)
{
if (!attrs.wrapIf())
{
el.replaceWith(el.html());
}
}
}
}
}
]);
用法:
<a href="/" data-my-wrap-if="list.indexOf(currentItem) %2 === 0">Some text</a>
<a href="/" remove-tag-if="$last">{{user}}'s articles</a>
“某些文本”只有在满足条件时才会成为链接。修改了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));
}
};
}]);
用法:
<a href="/" data-my-wrap-if="list.indexOf(currentItem) %2 === 0">Some text</a>
<a href="/" remove-tag-if="$last">{{user}}'s articles</a>
我个人不喜欢这种方法的一点是,它将这两个元素都保留在DOM中,而ng switch
修改DOM。据我所知。@akonsu ng如果你想要什么。有可能消除吗?仅itNope中的文本,不使用ngSwitch
span
没有样式修改,它只是内联文本,为什么要删除它?只是好奇而已。我尝试将“ng switch when”设置为“On”,并在其后面加上“ng bind”,希望“ng bind”仅在“ng switch when”匹配时才计算。但似乎angular不是这样工作的。angular就是这样工作的。您完全可以使用ngBind
以及ngSwitchWhen
我的意思是我试图在“开启”时同时设置“ng开关”和“ng开关”。控制台中出现错误:“参数“?”是必需的”。不管怎样,谢谢。有没有办法让条件接受一个角度表达式呢?目前看来,它只是纯Javascript。我想调用一个函数或使用$scope对象。@CarlosP是的,用隔离作用域声明一个指令,然后使该作用域对象的一个字段的值为@
。我可能应该重写这个答案;这不是我今天要做的。如果你有时间重写答案来演示如何做,那真的很方便-谢谢@凯西将非常感谢你提到的最新答案!工作得很好,但我不确定,如果标记体使用指向promise/lazy加载对象的表达式,它会工作吗?--在我们的示例中,如果{{user}}的值在运行时更改,文本会更新吗?