gpt4 book ai didi

javascript - 如何在 AngularJS 中有条件地应用指令?

转载 作者:数据小太阳 更新时间:2023-10-29 06:15:31 26 4
gpt4 key购买 nike

我想使用 ngAttr 有条件地应用一个简单的指令。我不明白为什么总是显示我的指令。因此,如果我有一个 undefined/false 变量,我想应用我的指令:dirr

When using ngAttr, the allOrNothing flag of $interpolate is used, so if any expression in the interpolated string results in undefined, the attribute is removed and not added to the element.

My code pen

<div ng-app="myApp" ng-controller="MainController" class="container-fluid">
<h2 ng-bind="currentVersion"></h2>
<hr>
<div ng-attr-dirr="hidden || undefined">Default div</div>
</div>

angular.module('myApp',[])
.directive('dirr', function(){
return {
restrict:'AE',
template:'<div>Div from directive</div>'
}
})
.controller('MainController',['$scope', function($scope){
$scope.currentVersion = 'Angular 1.3.6';
$scope.hidden = undefined;
}])
;

最佳答案

您可以使用 AngularJS 的内置指令 ng-if 来检查条件并有条件地执行它。

示例:

<div ng-if="{some_condition}">
<dirr></dirr> <!--Execute the directive on the basis of outcome of the if condition-->
</div>

关于javascript - 如何在 AngularJS 中有条件地应用指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35622702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com