Francisc
Francisc

Reputation: 80425

How to add ng-class to a directive's template?

What is the proper way of adding an ng-class expression to an element from inside a directive?

For example:

<div my-directive></div>

Inside myDirective, I want to make the element look like this:

<div my-directive ng-class="{visible:isVisible}"></div>

Should it be done in the compile function's first parameter, the tElement?
If so, how? Simply using setAttribute()?

Thanks.

Upvotes: 0

Views: 799

Answers (1)

michael
michael

Reputation: 16341

I would use a template and replace the original div to achieve this:

the directive:

.directive('myDirective', function(){
   return {
      restrict: 'A',
      template: '<div ng-class="{visible:isVisible}"></div>',
      replace: true,
      link: function($scope, elem, attrs){
         $scope.isVisble = true;
      }
   }
})

in you html:

<div my-directive></div>

How isVisible is set is only an example. You can do this in the directive controller, in the parent scope, in an isolated scope...

Upvotes: 2

Related Questions