How to conditionally apply a directive in AngularJS?

I want to apply a simple directive conditionally using ngAttr . I do not understand why my directive is always displayed. Therefore, if I have an undefined / false variable, I want to apply my directive: dirr .

When using ngAttr , the allOrNothing flag $ interpolation is used , therefore, if any expression in the interpolated string results in undefined , the attribute is deleted and not added to the element.

My pen code

<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; }]) ; 
+5
source share
3 answers

The answers are correct, and the sample code you provided works for small problems, but when the solution to this problem is executed in large applications, you can use this approach:

Updated pen

 <div ng-app="myApp" ng-controller="MainController" class="container-fluid"> <h2 ng-bind="currentVersion"></h2> <hr> <div dirr value="{{hidden}}">Default div</div> </div> .directive('dirr', function($log){ var directiveInstance = { restrict:'AE', scope:{ value:'@' }, link: function (scope, element, attrs, ctrl) { if(attrs.value === 'true'){ console.log('directive on !!'); $log.debug('element',element); element[0].innerHTML = '<div>hello ' + attrs.value + '</div>'; } else { console.log('directive off !!'); } } } return directiveInstance; }) 

This is tidier, and you cannot duplicate your code using the ngIf or ngSwitch directives in separate divs when you have something like:

 <table> <thead dirr value="{{statement}}"> <tr> <th> CrazyStuffHere... </th> <th> CrazyStuffHere... </th> .... </tr> </thead> </table> 
0
source

You can use the built-in AngelJS ng-if directive to check the condition and execute it conditionally.

Example:

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

Format Documentation

All Angular -provided directives match attribute name, tag name, comments, or class name

therefore, whenever angular matches a directive with an attribute name, it compiles the template and displays html regardless of the attribute value.

in any case, you can use the scope in the template.so directive to use ng-hide with the hidden scope property

angular.module ('MYAPP', [])

  .directive('dirr',function(){ return{ restrict:'AE', template:'<div ng-hide="hidden">Div from directive</div>', } }) .controller('MainController',['$scope', function($scope){ $scope.hidden=false; }]); 
+1
source

Source: https://habr.com/ru/post/1243824/


All Articles