2017-05-26 19 views
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'} 
"> 

這將是更好,如果你知道任何的方式來傳遞屬性返回風格OBJ爲NG-風格像波紋管這古怪不能正常工作的功能!

$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

只是將該屬性傳遞給函數(上,下,空閒或空字符串),並且該函數將向其元素應用正確的樣式。 – Karim

+0

請再次檢查我的問題。狀態很好,attr不起作用。那是奇怪的部分。如果你通過''color''它確實返回'{'color':'#ff0000'}'例如但不在DOM中顯示。 – DragonKnight

0

可以使用納克級爲好。

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>