2017-05-26 53 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>