Dor*_*hen 247 angularjs ng-class
我正在以下列方式使用angularjs ng-class:
<div class="bigIcon" data-ng-click="PickUp()"
ng-class="{first:'classA', second:'classB', third:'classC', fourth:'classC'}[call.State]"/>
Run Code Online (Sandbox Code Playgroud)
我想知道我是否可以使用if-else表达式,我可以做类似的事情:
<div class="bigIcon" data-ng-click="PickUp()"
ng-class="{first:'classA', second:'classB', else:'classC'}[call.State]"/>
Run Code Online (Sandbox Code Playgroud)
意思是call.State不同于first或second使用,classC而不是指定每个值.
谢谢!
Jos*_*ush 511
<div ng-class=" ... ? 'class-1' : ( ... ? 'class-2' : 'class-3')">
Run Code Online (Sandbox Code Playgroud)
例如 :
<div ng-class="apt.name.length >= 15 ? 'col-md-12' : (apt.name.length >= 10 ? 'col-md-6' : 'col-md-4')">
...
</div>
Run Code Online (Sandbox Code Playgroud)
并确保你的同事可以读取它:)
Dot*_*Dot 107
你可以尝试使用这样的函数:
<div ng-class='whatClassIsIt(call.State)'>
Run Code Online (Sandbox Code Playgroud)
然后将您的逻辑放入函数本身:
$scope.whatClassIsIt= function(someValue){
if(someValue=="first")
return "ClassA"
else if(someValue=="second")
return "ClassB";
else
return "ClassC";
}
Run Code Online (Sandbox Code Playgroud)
我做了一个小例子:http://jsfiddle.net/DotDotDot/nMk6M/
joe*_*wen 61
我有一种情况,我需要两个'如果'的陈述,既可以成为现实,也可以是'其他'或默认,如果两者都不是真的,不确定这是否是对Jossef答案的改进,但对我来说似乎更清晰:
ng-class="{'class-one' : value.one , 'class-two' : value.two}" class="else-class"
Run Code Online (Sandbox Code Playgroud)
在value.one和value.two为真的情况下,它们优先于.else-class
Lew*_*Hai 13
显然!我们可以使用以下完整示例来创建一个返回CSS类名的函数.

CSS
<style>
.Red {
color: Red;
}
.Yellow {
color: Yellow;
}
.Blue {
color: Blue;
}
.Green {
color: Green;
}
.Gray {
color: Gray;
}
.b{
font-weight: bold;
}
</style>
Run Code Online (Sandbox Code Playgroud)
JS
<script>
angular.module('myapp', [])
.controller('ExampleController', ['$scope', function ($scope) {
$scope.MyColors = ['It is Red', 'It is Yellow', 'It is Blue', 'It is Green', 'It is Gray'];
$scope.getClass = function (strValue) {
if (strValue == ("It is Red"))
return "Red";
else if (strValue == ("It is Yellow"))
return "Yellow";
else if (strValue == ("It is Blue"))
return "Blue";
else if (strValue == ("It is Green"))
return "Green";
else if (strValue == ("It is Gray"))
return "Gray";
}
}]);
</script>
Run Code Online (Sandbox Code Playgroud)
然后
<body ng-app="myapp" ng-controller="ExampleController">
<h2>AngularJS ng-class if example</h2>
<ul >
<li ng-repeat="icolor in MyColors" >
<p ng-class="[getClass(icolor), 'b']">{{icolor}}</p>
</li>
</ul>
<hr/>
<p>Other way using : ng-class="{'class1' : expression1, 'class2' : expression2,'class3':expression2,...}"</p>
<ul>
<li ng-repeat="icolor in MyColors">
<p ng-class="{'Red':icolor=='It is Red','Yellow':icolor=='It is Yellow','Blue':icolor=='It is Blue','Green':icolor=='It is Green','Gray':icolor=='It is Gray'}" class="b">{{icolor}}</p>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
492018 次 |
| 最近记录: |