Angularjs 指令:如何在属性更改后更新模板中的 ng-class

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

我有以下指令:

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

})();

我希望模板代码中的ng-class表达式在html中有is-active属性的情况下添加activeclass,对于实例...

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

...将是 html 并且 Item 2 菜单项将被激活。如您所见,我已经实现了一个 link 函数,我试图在其中评估是否存在名为 is-active 的属性。如果存在,那么我将设置一个名为 scope.active 的范围变量。然而,就模板中的 ng-class 而言,此范围变量始终未定义。

谁能解释一下如何解决这个问题?

非常感谢!

您不需要 scope 前缀,评估上下文是 scope 对象本身:

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

您也不需要 $watch 只需在 link 函数中设置 scope.active = 'isActive' in attr;