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

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

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

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

我该怎么做呢?


当前回答

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

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

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

其他回答

就像@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>

编辑:

好吧,我以前不知道AngularJS通常指的是Angular v1版本,而只指Angular v2+

这个答案只适用于Angular

把这个留在这里,以备将来参考。


不知道它对你们来说是如何工作的,但在Angular 9中,我必须像这样用括号括起ngStyle:

[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>

简单的例子:

<div ng-style="isTrue && {'background-color':'green'} || {'background-color': 'blue'}" style="width:200px;height:100px;border:1px solid gray;"></div>

{'background-color':'green'}返回true

或者是同样的结果:

<div ng-style="isTrue && {'background-color':'green'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>

其他条件可能性:

<div ng-style="count === 0 && {'background-color':'green'}  || count === 1 && {'background-color':'yellow'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>