I\'m trying to conditionally apply a directive to an element based on its class.
Here\'s a simple case of my issue, see the results in this fiddle. For this example,
ng-class
just sets classes on the DOM, after the compilation process.
Perhaps a better way to apply the directive would be through an HTML attribute:
Of course, this is not conditional, but I would leave the conditioning to the directive:
Hello
Condition
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 the directive name is testCase
rather than testcase
, the scope: {'condition': '='},
bit ensures that the condition attribute is synchronized and available as scope.condition
and the watch
evaluates the second argument every time the expression on the first changes value. JsFiddle over here.
Perhaps you should also look into ng-switch:
Contents when conditionFunction() returns true
Contents when conditionFunction() returns false