首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ng-style指令中基于多个条件应用多个样式?

如何在ng-style指令中基于多个条件应用多个样式?
EN

Stack Overflow用户
提问于 2017-05-27 06:23:47
回答 2查看 6.5K关注 0票数 3

在angular中,我需要根据不同的条件应用不同的样式属性,但它不是以这种方式工作的,我只能使用条件表达式应用2个条件。

代码语言:javascript
复制
<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,就像bellow一样,这是非常不起作用的!

代码语言:javascript
复制
$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')">
EN

回答 2

Stack Overflow用户

发布于 2017-05-27 06:36:01

是的,您可以使用函数来指定更复杂的条件。

代码语言:javascript
复制
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']; 
)};

然后是模板

代码语言:javascript
复制
<div ng-style="applyStyle(status)"></div>
票数 3
EN

Stack Overflow用户

发布于 2017-05-27 06:49:13

您也可以使用ng-class。

代码语言:javascript
复制
function DemoCtrl($scope) {
    $scope.status = 'up'
}
代码语言:javascript
复制
.green {
    color: green;
    background-color:green;
}
.red {
    color: red;
    background-color:red
}
.yellow {
    color: yellow;
    background-color:yellow;
}
代码语言:javascript
复制
<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>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44210899

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档