簡體   English   中英

自定義指令中的條件ngClass

[英]Conditional ngClass inside a custom directive

我正在嘗試了解隔離范圍。

可以說,我有一個簡單的指令:

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

它將“ {'enabled':data.status =='enabled'}”放入類。 每當數據更新時,我需要編譯它還是如何使其成為評估類?

在瀏覽器上,我看到了

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

我想看看

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

使用模板函數將ng-class從myDirective傳遞到模板:

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

}

或者,您可以使用$ 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;
        }
     }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM