2017-05-26 6 views
2

アングルでは、異なる条件に基づいて異なるスタイル属性を適用する必要がありますが、このようには動作しません。条件付きの条件を2つ適用することしかできません。ngスタイルのディレクティブで複数の条件に基づいて複数のスタイルを適用するにはどうすればよいですか?

<div ng-style=" 
    (status=="up") ?{'background-color':'green' ,'color':'green'} 
    (status=="down")?{'background-color':'red' ,'color':'red'} 
    (status=="idle")?{'background-color':'yellow','color':'yellow'} 
    (status=="") ?{'background-color':'grey' ,'color':'grey'} 
"> 

あなたが変なふうに動作していない怒鳴るようngのスタイルのスタイルOBJを返す関数に属性を渡すためにどのような方法を知っていれば、それは良いだろう!

$scope.styleFn(status,attr) { 
     (status=="up") ?{attr:'green'} 
     (status=="down")?{attr:'red'} 
     (status=="idle")?{attr:'yellow'} 
     (status=="") ?{attr:'grey'} 
} 

<div ng-style="styleFn('up','background-color')"> 

答えて

1

はい、より複雑な条件を指定するために関数を使用できます。

var style = { 
    'up': {'background-color':'green' ,'color':'green'}, 
    'down': {'background-color':'red' ,'color':'red'}, 
    'idle': {'background-color':'yellow' ,'color':'yellow'}, 
    'default': {'background-color':'grey' ,'color':'grey'} 
} 

$scope.applyStyle = function(status) { 
    //the status is the key to get the target style 
    return status ? style[status] : style['default']; 
)}; 

、テンプレート

<div ng-style="applyStyle(status)"></div> 
+0

が、どのように関数に属性を渡し、カスタマイズされたスタイルを生成していますか?それは奇妙なことではありません。 – DragonKnight

+0

関数に属性(up、down、idle、または空文字列)を渡すだけで、関数は要素に正しいスタイルを適用するという魔法を実行します。 – Karim

+0

私の質問をもう一度チェックしてください。ステータスは正常ですが、attrは機能していません。それは奇妙な部分です。 '' color''を渡すと '{'color': '#ff0000'}'が返されますが、DOMには表示されません。 – DragonKnight

0

はあなたにもNG-クラスを使用することができます。

右ザッツ

function DemoCtrl($scope) { 
 
    $scope.status = 'up' 
 
}
.green { 
 
    color: green; 
 
    background-color:green; 
 
} 
 
.red { 
 
    color: red; 
 
    background-color:red 
 
} 
 
.yellow { 
 
    color: yellow; 
 
    background-color:yellow; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app> 
 
    
 
    <table ng-controller="DemoCtrl"> 
 
     <tr ng-class="{'green': status == 'up','red':status== 'down' ,'yellow': status== 'idle' } "> 
 
      <td style="color:white;">Your status is {{status}}</td> 
 
     </tr> 
 
    </table> 
 
</div>

関連する問題