2

If I have something like this

<div ng-class="{'breakfast': meal == 'eggs'}"></div> 

Now I need to create a directive that would add the same thing, so doing this:

restrict: 'C' scope: meal:"&" link:(scope, element, attr)-> element.attr('ng-class', "{'breakfast': meal == 'eggs'}") 

adds the attribute to the DOM, but then nothing happens, when meal == 'eggs' it doesn't add breakfast class to the element. What am I doing wrong?

ps. I can of course do it with element.addClass and element.removeClass but then the animation would only work when I add the class, but wouldn't for the removal (if I have css styles like .breakfast-add, .breakfast-remove etc.

2
  • use '=' rather than '&', '&' is for passing function Commented Jun 17, 2014 at 0:49
  • So the main reason why I needed that is to have an easier way to bind class based animations in directive, instead of doing ng-class="{'breakfast... etc. all the time. Ended up using $animate.addClass, but the question itself remains open Commented Jun 17, 2014 at 22:28

1 Answer 1

1

Instead of modifying the element's attributes at link or compile time, you can use ng-class in the directive's template and use a scope variable with your classes. It works for me in the following example, and it seems to be cleaner:

HTML:

<div ng-app="app"> <div class="meal: eggs;">xxx</div> </div> 

JS:

angular.module('app', []) .directive('meal', function () { return { template: '<div ng-class="classes" ng-transclude></div>', transclude: true, restrict: 'C', scope: { meal: '@' }, link: function (scope) { scope.classes = { breakfast: (scope.meal == 'eggs') }; } }; }); 
Sign up to request clarification or add additional context in comments.

2 Comments

It's a class directive though... I don't want to transclude (do I?), it would create another element though?
Yes, it adds an element to the DOM which wraps the original content. This will not help in your case (the animation thing was not clear at the time of writing this answer ;) ) I think the usual way to add classes is element.addClass in the compile function (but will not work with CSS animations, too).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.