How do I apply an AngularJS directive based on a class set by ng-class? -


i'm trying conditionally apply directive element based on class.

here's simple case of issue, see results in fiddle. example, i'm using map of class names booleans form of ng-class true; in actual case i'd use boolean result of function.

markup:

<div ng-app="example">   <div class="testcase">     have directive applied expect   </div>   <div ng-class="{'testcase':true}">     not have directive applied expect   </div> </div> 

js:

angular.module('example', [])   .directive('testcase', function() {       return {           restrict: 'c',           link: function(scope, element, attrs) {               element.css('color', 'red');           }       }     }   ); 

why isn't directive being applied div that's getting class through ng-class? misunderstanding order in angularjs processing directives?

how should conditionally applying directive element based on evaluation of expression?

ng-class sets classes on dom, after compilation process.

perhaps better way apply directive through html attribute:

<div test-case> 

of course, not conditional, leave conditioning directive:

<div ng-app="example" ng-controller="examplectrl">     <div test-case condition="dynamiccondition">hello</div>     <input type="checkbox" ng-model="dynamiccondition"/> condition  </div> 

and

angular.module('example', [])     .controller('examplectrl', function ($scope) {         $scope.dynamiccondition = false;     })     .directive('testcase', function () {     return {         restrict: 'a',         scope: {             'condition': '='         },         link: function (scope, element, attrs) {             scope.$watch('condition', function(condition){                 if(condition){                     element.css('color', 'red');                 }                 else{                     element.css('color', 'black');                 };             });         }     } }); 

notice directive name testcaserather testcase, scope: {'condition': '='}, bit ensures condition attribute synchronized , available scope.condition , watch evaluates second argument every time expression on first changes value. jsfiddle over here.

perhaps should ng-switch:

<div ng-switch="conditionfunction()">   <div ng-when="true" test-case>contents when conditionfunction() returns true</div>   <div ng-when="false">contents when conditionfunction() returns false</div> </div> 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -