2017-02-22 7 views
0

は、私が入ってくるparametesの依存要素にクラスを設定するカスタムディレクティブ角度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

のparamを渡すときのディレクトリは、クラスを設定しません。引用符がありません。文字列を渡す必要があります。そうでない場合、angleはactiveを親スコープ変数としてコンパイルします。 http://jsfiddle.net/9h29R/73/

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

@Slavaを確認してください。 Kはエラーを犯した。楽しみのためだけに、ここにスタイルを設定する別の方法、および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> 

フィドラー

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

関連する問題