我是这样处理我的问题的:

ng-style="{ width: getTheValue() }"

但是为了避免在控制器端使用这个函数,我更倾向于这样做:

ng-style="{ width: myObject.value == 'ok' ? '100%' : '0%' }"

我该怎么做呢?


当前回答

对于多个独立的条件,我像下面这样做,它很有魅力:

<div ng-style="{{valueFromJS}} === 'Hello' ? {'color': 'red'} : {'color': ''} && valueFromNG-Repeat === '{{dayOfToday}}' ? {'font-weight': 'bold'} : {'font-weight': 'normal'}"></div>

其他回答

你可以这样做:

ng-style="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"

就像@Yoshi说的,从angular 1.1.5开始你就可以不用做任何改变就可以使用它了。

如果你使用angular < 1.1.5,你可以使用ng-class。

.largeWidth {
    width: 100%;
}

.smallWidth {
    width: 0%;
}

// [...]

ng-class="{largeWidth: myVar == 'ok', smallWidth: myVar != 'ok'}"

一般来说,您可以结合使用ng-if和ng-style合并背景图像的条件更改。

<span ng-if="selectedItem==item.id"
              ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_active.png)','background-size':'52px 57px','padding-top':'70px','background-repeat':'no-repeat','background-position': 'center'}"></span>
        <span ng-if="selectedItem!=item.id"
              ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_deactivated.png)','background-size':'52px 57px','padding-top':'70px','background-repeat':'no-repeat','background-position': 'center'}"></span>

对于多个独立的条件,我像下面这样做,它很有魅力:

<div ng-style="{{valueFromJS}} === 'Hello' ? {'color': 'red'} : {'color': ''} && valueFromNG-Repeat === '{{dayOfToday}}' ? {'font-weight': 'bold'} : {'font-weight': 'normal'}"></div>

如果你想和表达一起使用,正确的方法是:

<span class="ng-style: yourCondition && {color:'red'};">Sample Text</span>

但是最好的方法是使用ng-class