javascriptangularjsangularjs-directiveangularjs-ng-class

Angular dirrectives and ng-class


Suppose a directive with html e.g. in component.html like

<div class="text-field"
     ng-class="{'classA': varA}">
....
</div>

then I'm trying to do...

<component ng-class="{'classB': varB}"></component>

After that in ng-class I'm having something like {'classB': varB} {'classA': varA} that is obviously not working.

The problem is that I cannot change component.html but I need to add/remove class on keyup (depending on criteria). Is it possible to add ng-class in my situation or mayb there's another way to add/remove class?


Solution

  • Try adding another directive that adds the class via script, something like

    .directive('myDir',function(){
      return {
        scope:{
         varB:'='
        },
        link: function($scope,$element){
          if($scope.varB)
            $element.addClass('classB');
        }
      }
    });
    

    and use like:

    <component ng-class="{'classB': varB}" my-dir var-b="something"></component>