iLemming
iLemming

Reputation: 36166

Class directive that adds ng-class

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.

Upvotes: 2

Views: 93

Answers (1)

Pascal Ockert
Pascal Ockert

Reputation: 984

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')
      };
    }
  };
});

Upvotes: 1

Related Questions