我是这样处理我的问题的:
ng-style="{ width: getTheValue() }"
但是为了避免在控制器端使用这个函数,我更倾向于这样做:
ng-style="{ width: myObject.value == 'ok' ? '100%' : '0%' }"
我该怎么做呢?
我是这样处理我的问题的:
ng-style="{ width: getTheValue() }"
但是为了避免在控制器端使用这个函数,我更倾向于这样做:
ng-style="{ width: myObject.value == 'ok' ? '100%' : '0%' }"
我该怎么做呢?
当前回答
编辑:
好吧,我以前不知道AngularJS通常指的是Angular v1版本,而只指Angular v2+
这个答案只适用于Angular
把这个留在这里,以备将来参考。
不知道它对你们来说是如何工作的,但在Angular 9中,我必须像这样用括号括起ngStyle:
[ng-style]="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"
否则就不行
其他回答
此外,三元操作符的语法也可以工作:
ng-style="<$scope.var><condition> ? {
'<css-prop-1>':((<value>) / (<value2>)*100)+'%',
'<css-prop-2>':'<string>'
} : {
'<css-prop-1>':'<string>',
'<css-prop-2>':'<string>'
}"
其中<value>为$scope属性值。 在示例:
ng-style="column.histograms.value=>0 ?
{
'width':((column.histograms.value) / (column.histograms.limit)*100)+'%',
'background':'#F03040'
} : {
'width':'1px',
'background':'#2E92FA'
}"
```
这允许对CSS属性值进行一些计算。
对于单个css属性
ng-style="1==1 && {'color':'red'}"
对于下面的多个css属性可以参考
ng-style="1==1 && {'color':'red','font-style': 'italic'}"
用条件表达式替换1==1
我正在使用ng-class添加风格:-
ng-class="column.label=='Description' ? 'tableStyle':
column.label == 'Markdown Type' ? 'Mtype' :
column.label == 'Coupon Number' ? 'couponNur' : ''
"
在angular.js中使用三元操作符和ng-class指令来给出样式。 然后在.css或.scss文件中定义类的样式。如:-
.Mtype{
width: 90px !important;
min-width: 90px !important;
max-width: 90px !important;
}
.tableStyle{
width: 129px !important;
min-width: 129px !important;
max-width: 129px !important;
}
.couponNur{
width: 250px !important;
min-width: 250px !important;
max-width: 250px !important;
}
你可以这样做:
ng-style="{ 'width' : (myObject.value == 'ok') ? '100%' : '0%' }"
如果你想和表达一起使用,正确的方法是:
<span class="ng-style: yourCondition && {color:'red'};">Sample Text</span>
但是最好的方法是使用ng-class