【问题标题】:Angularjs Directive: How to update ng-class in template after change in attributeAngularjs指令:如何在属性更改后更新模板中的ng-class
【发布时间】:2016-01-23 22:39:48
【问题描述】:

我有以下指令:

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

})();

如果html中有is-active属性,我希望模板代码中的ng-class表达式添加active类,例如...

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

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

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

非常感谢!

【问题讨论】:

    标签: javascript angularjs attributes directive ng-class


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢!对于这两个建议。我添加了 $watch 以查看这是否解决了我最初的尝试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 2016-11-29
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多