angularjs
2017-02-22 201 views 0 likes 
0

我試着編寫自定義指令角JS,取決於傳入指標的影響的集類元素:爲什麼指令不會設置類?

angular.module('hello', []) 
    .directive("testCase", function(){ 

    return { 
     restrict: 'A', 
     scope: { 
      'condition': '=' 
     }, 
     link: function (scope, element, attrs) { 
      switch (scope.condition) { 
       case "pending": 
       element.css('color', 'yellow'); 
       break; 
       case 'active': 
       element.css('color', 'green'); 
       break; 
       case "archived": 
       case "finished": 
       case "completed": 
       element.css('color', 'gray'); 
       break; 
       } 

     } 
     } 
}); 

http://jsfiddle.net/9h29R/71/

但目錄中不設置類,當我通過參數「活躍」

+2

其不是目錄其指令 – Sajeetharan

回答

1

你只是缺少報價。您需要傳遞字符串,否則角將編譯active作爲父範圍變量。檢查工作小提琴:http://jsfiddle.net/9h29R/73/

<div ng-app="hello"> 
    <div test-case condition="'active'">Active</div>  
</div> 
1

@Slava。 K cought錯誤。只是爲了好玩,這裏是設置樣式的另一種方式,並使用attrs.$set元素上的任何其他屬性:

的JS

angular.module('hello', []) 
    .directive("testCase", function() { 

    return { 
     restrict: 'A', 
     scope: { 
     'condition': '=' 
     }, 
     link: function(scope, element, attrs) { 

     var setStyle = function() { 

      switch (attrs.condition) { 

      case "pending": 
       return "color: yellow" 
      case "active": 
       return "color: green" 
      case "archived": 
      case "finished": 
      case "completed": 
       return "color: gray" 
      } 
     }; 

     attrs.$set('style', setStyle()); 
     } 

    } 
    }); 

標記

<div ng-app="hello"> 
    <div test-case condition="active">Active</div> 
    <div test-case condition="pending">Pending</div> 
    <div test-case condition="archived">Archived</div> 
    <div test-case condition="finished">Finished</div> 
</div> 

的Fiddler

http://jsfiddle.net/zh9u45nn/2/

相關問題