在自定义AngularJS指令中将ng-class绑定到本地作用域表达式



我希望我的自定义指令能够根据绑定到父范围的一些值预处理自己的类。然而,我似乎无法让指令设置自己的ng类并在局部范围内执行函数。

directive('testDirective',function(){
     restrict: 'E',
     scope: {
         inputValue: '='
     },
     template: '<div>dynamically styled content</div>',
     bindToController: true,
     controllerAs: 'ctrl',
     compile: function(element){
          element.attr('ng-class', 'ctrl.getClass()');
     },
     controller: function(){
         this.getClass = function(){
             //return array of classes based on value of this.inputValue
         }
     }
});

不幸的是,没有样式得到应用,因为表达式从来没有计算过,只是被赋值为字符串。当我检查DOM元素

时,我看到了以下内容
ng-class="ctrl.getClass()"

我意识到我可以使用jQuery在链接函数中添加我的类,但这样它们就不会绑定到我的数据。如果可能的话,我也希望避免使用$watch。

欢迎任何想法!

假设你有一个这样的css文件:

.myButton1 {
  color: red;
}
.myButton2 {
  color: blue;
}

在你的指令中,你可以使用ng-class:

directive('testDirective',function(){
     restrict: 'E',
     scope: {
         inputValue: '='
     },
     template: '<div ng-class="ctrl.getClass()">dynamically styled content</div>',
     bindToController: true,
     controllerAs: 'ctrl',
     controller: function(){
         this.getClass(){
           return (ctrl.inputValue === 'something' ? "myButton1" : "myButton2");
         }
     }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

getClass方法必须返回有效的预定义css类,一个或一个数组

最新更新