Search code examples
javascriptangularjsattributesdirectiveng-class

Angularjs Directive: How to update ng-class in template after change in attribute


I have the following directive:

(function() {
  'use strict';

  angular
    .module('app.navbar')
    .directive('myItem', myItem);

  function myItem() {
    var directive = {
      restrict: 'E',
      transclude: true,
      scope: {
        href: '@'
      },
      template : 
        '<li ng-class="{\'active\' : scope.active}"><a href="{{href}}" ng-transclude></a></li>',
      link : link
    };
    return directive;

    /////////////////

    function link(scope, elem, attr) {
      scope.$watch(function() {
        scope.active = ('isActive' in attr);
        console.log("scope active: " + scope.active);
      })
    }
  }

})();

I want the ng-class expression in the template code to add the active class if there is an is-active attribute in the html, for instance...

<my-item>Item 1</my-item>
<my-item is-active>Item 2</my-item>

...would be the html and the Item 2 menu item would be activated. As you can see I've implemented a link function where I'm trying to evaluate whether there is an attribute called is-active. If this exists then I'm setting a scope variable called scope.active. As far as the ng-class in the template can discern, however, this scope variable always remains undefined.

Can anyone explain how to fix this?

Many thanks!


Solution

  • You don't need scope prefix, evaluation context is scope object itself:

    template: '<li ng-class="{active: active}"><a href="{{href}}" ng-transclude></a></li>',
    

    You also don't need $watch just set scope.active = 'isActive' in attr; in link function.