Bind ng-class to a local scope expression in custom AngularJS directive

1.2k Views Asked by At

I would like my custom directive to be able to pre-process its own classes based on some values bound to its parent scope. However, I can't seem to get the directive to set its own ng-class and execute a function on the local scope.

directive('testDirective',function(){
     restrict: 'E',
     scope: {
         inputValue: '='
     },
     template: '<div>dynamically styled content</div>',
     bindToController: true,
     controllerAs: 'ctrl',

     compile: function(element){
          element.attr('ng-class', 'ctrl.getClass()');
     },

     controller: function(){
         this.getClass = function(){
             //return array of classes based on value of this.inputValue
         }
     }
});

Unfortunately no styles get applied as the expression is never evaluated and is just being assigned as a string. I see the following when I inspect the DOM element

ng-class="ctrl.getClass()"

I realize that I could just use jQuery to add my classes in the link function, but then they would not be bound to my data. I was also hoping to avoid using $watch if at all possible.

Any ideas are welcome!

1

There are 1 best solutions below

1
On

Lets imagine you have a css file like this:

.myButton1 {
  color: red;
}

.myButton2 {
  color: blue;
}

The in your directive you could do this with ng-class:

directive('testDirective',function(){
     restrict: 'E',
     scope: {
         inputValue: '='
     },
     template: '<div ng-class="ctrl.getClass()">dynamically styled content</div>',
     bindToController: true,
     controllerAs: 'ctrl',
     controller: function(){
         this.getClass(){
           return (ctrl.inputValue === 'something' ? "myButton1" : "myButton2");
         }
     }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

Your getClass method must return valid pre-defined, css classes, one or an array of them.