Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply directive conditionally in AngularJS?

I want to apply a simple directive conditionally using ngAttr. I don't understand why my directive is always displayed. So if I have an undefined / false variable I want to apply my directive: 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;
 }])
; 
like image 915
que1326 Avatar asked Feb 25 '16 09:02

que1326


People also ask

What is Ng ATTR?

If expression is undefined, still fires directive link function, even though the directive is not added in the DOM. #16441.

What are the directives in angular?

In Angular, Directives are defined as classes that can add new behavior to the elements in the template or modify existing behavior. The purpose of Directives in Angular is to maneuver the DOM, be it by adding new elements to DOM or removing elements and even changing the appearance of the DOM elements.


1 Answers

You can make use of AngularJS's inbuilt directive ng-if to check for 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>
like image 114
Shashank Avatar answered Sep 29 '22 06:09

Shashank