angularjs
2017-02-22 104 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/

相关问题