自定义指令中的条件ngClass

时间:2014-08-15 07:07:07

标签: javascript angularjs

我正在尝试了解孤立范围。

让我们说,我有一个简单的指令:

HTML:

<my-directive options = "data"></my-directive>

JS:

angular.module('myapp.directive').
    directive('myDirective', function() {
     return {
        template: '<a href = "{{href}}" class = "class"></a>',
         restrict: 'E',
         replace: 'true',
         scope: {
           options = "=options"
         },
         link: function(scope, element, attrs) {
            scope.$watch('options', function(data) {
              scope.class = data.class;
              scope.href = data.href;
            }
         }

    }

有效。 现在我想添加ng-class:

<my-directive ng-class = "{'enabled': data.status == 'enabled'}" options = "data"></my-directive>

我试过了:

scope : {
   options: '=options',
   ngClass: "="
}

scope.$watch("ngClass", function(value) {
   scope.class += value;
}

它将&#34; {&#39;已启用&#39;:data.status ==&#39;}&#39;}&#34; 添加到课程中。我是否需要编译它或者如何在每次更新数据时使其成为评估类?

在浏览器上我看到了

<a href = "{{href}}" class = "class "{'enabled': data.status == 'enabled'}""></a>

我想看看

<a href = "{{href}}" class = "class enabled"></a>

2 个答案:

答案 0 :(得分:1)

使用模板函数将myDirective中的ng-class传递给模板:

<my-directive ng-class = "{'enabled': data.status == 'enabled'}" options = "data">
</my-directive>

指令

angular.module('myapp.directive').
directive('myDirective', function() {
 return {
    template: function(element, attr) { 
         return '<a href = "{{href}}" class = "class" ng-class="' + attr.ngClass + '"></a>'
     },
     restrict: 'E',
     replace: 'true',
     scope: {
       options = "=options"
     },
     link: function(scope, element, attrs) {
        scope.$watch('options', function(data) {
          scope.class = data.class;
          scope.href = data.href;
        }
     }

}

答案 1 :(得分:0)

或者,您可以使用$ eval将ngClass表达式转换为对象,然后将其绑定到指令的隔离范围内的范围变量,以便可以在模板中使用:

HTML

<my-directive ng-class = "{'enabled': data.status == 'enabled'}" options = "data">
</my-directive>

指令

angular.module('myapp.directive').
directive('myDirective', function() {
 return {
    template: function(element, attr) { 
         return '<a href = "{{href}}" class = "class" ng-class="modelClass"></a>'
     },
     controller: function($scope, $element, $attrs) {
        $scope.modelClass = $scope.$eval($attrs.ngClass);
     },
     restrict: 'E',
     replace: 'true',
     scope: {
       options = "=options"
     },
     link: function(scope, element, attrs) {

        scope.$watch('options', function(data) {
          scope.class = data.class;
          scope.href = data.href;
        }
     }

}