CSS 有条件地应用课程的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7792652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to conditionally apply a class?
提问by respectTheCode
Lets say you have an array that is rendered in a ul
with an li
for each element and a property on the controller called selectedIndex
. What would be the best way to add a class to the li
with the index selectedIndex
in AngularJS?
比方说您有一个呈现的阵列ul
与li
每个元素,并呼吁在控制器上的属性selectedIndex
。将类添加到AngularJS 中li
的索引的最佳方法是selectedIndex
什么?
I am currently duplicating (by hand) the li
code and adding the class to one of the li
tags and using ng-show
and ng-hide
to show only one li
per index.
我目前正在复制(手动)li
代码并将类添加到li
标签之一,并使用ng-show
和ng-hide
仅显示li
每个索引一个。
回答by orcun
If you don't want to put CSS class names into Controller like I do, here is an old trick that I use since pre-v1 days. We can write an expression that evaluates directly to a class name selected, no custom directives are necessary:
如果你不想像我一样将 CSS 类名放入 Controller 中,这里有一个我从 v1 之前使用的老技巧。我们可以编写一个直接计算为selected类名的表达式,不需要自定义指令:
ng:class="{true:'selected', false:''}[$index==selectedIndex]"
Please note the old syntax with colon.
请注意带有冒号的旧语法。
There is also a new better way of applying classes conditionally, like:
还有一种新的更好的有条件应用类的方法,例如:
ng-class="{selected: $index==selectedIndex}"
Angular now supports expressions that return an object. Each property (name) of this object is now considered as a class name and is applied depending on its value.
Angular 现在支持返回对象的表达式。该对象的每个属性(名称)现在都被视为一个类名,并根据其值进行应用。
However these ways are not functionally equal. Here is an example:
然而,这些方式在功能上并不相同。下面是一个例子:
ng-class="{admin:'enabled', moderator:'disabled', '':'hidden'}[user.role]"
We could therefore reuse existing CSS classes by basically mapping a model property to a class name and at the same time keep CSS classes out of Controller code.
因此,我们可以通过基本上将模型属性映射到类名来重用现有的 CSS 类,同时将 CSS 类保留在控制器代码之外。
回答by Mark Rajcok
ng-classsupports an expression that must evaluate to either
ng-class支持一个表达式,该表达式必须计算为
- A string of space-delimited class names, or
- An array of class names, or
- A map/object of class names to boolean values.
- 一串以空格分隔的类名,或
- 类名数组,或
- 类名到布尔值的映射/对象。
So, using form 3) we can simply write
所以,使用形式 3) 我们可以简单地写
ng-class="{'selected': $index==selectedIndex}"
See also How do I conditionally apply CSS styles in AngularJS?for a broader answer.
另请参阅如何在 AngularJS 中有条件地应用 CSS 样式?以获得更广泛的答案。
Update: Angular 1.1.5 has added support for a ternary operator, so if that construct is more familiar to you:
更新:Angular 1.1.5 增加了对三元运算符的支持,所以如果你更熟悉这个结构:
ng-class="($index==selectedIndex) ? 'selected' : ''"
回答by skmvasu
My favorite method is using the ternary expression.
我最喜欢的方法是使用三元表达式。
ng-class="condition ? 'trueClass' : 'falseClass'"
Note:Incase you're using a older version of Angular you should use this instead,
注意:如果您使用的是旧版本的 Angular,您应该改用它,
ng-class="condition && 'trueClass' || 'falseClass'"
回答by stefano
I'll add to this, because some of these answers seem out of date. Here's how I do it:
我会补充一点,因为其中一些答案似乎已经过时。这是我的方法:
<class="ng-class:isSelected">
Where 'isSelected' is a javascript variable defined within the scoped angular controller.
To more specifically address your question, here's how you might generate a list with that:
其中 'isSelected' 是在作用域角度控制器中定义的 javascript 变量。
为了更具体地解决您的问题,您可以通过以下方式生成列表:
HTML
HTML
<div ng-controller="ListCtrl">
<li class="ng-class:item.isSelected" ng-repeat="item in list">
{{item.name}}
</li>
</div>
JS
JS
function ListCtrl($scope) {
$scope.list = [
{"name": "Item 1", "isSelected": "active"},
{"name": "Item 2", "isSelected": ""}
]
}
See: http://jsfiddle.net/tTfWM/
回答by stefano
Here is a much simpler solution:
这是一个更简单的解决方案:
function MyControl($scope){
$scope.values = ["a","b","c","d","e","f"];
$scope.selectedIndex = -1;
$scope.toggleSelect = function(ind){
if( ind === $scope.selectedIndex ){
$scope.selectedIndex = -1;
} else{
$scope.selectedIndex = ind;
}
}
$scope.getClass = function(ind){
if( ind === $scope.selectedIndex ){
return "selected";
} else{
return "";
}
}
$scope.getButtonLabel = function(ind){
if( ind === $scope.selectedIndex ){
return "Deselect";
} else{
return "Select";
}
}
}
.selected {
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-app ng-controller="MyControl">
<ul>
<li ng-class="getClass($index)" ng-repeat="value in values" >{{value}} <button ng-click="toggleSelect($index)">{{getButtonLabel($index)}}</button></li>
</ul>
<p>Selected: {{selectedIndex}}</p>
</div>
回答by Lèse majesté
I faced a similar problem recently and decided to just create a conditional filter:
我最近遇到了类似的问题,决定只创建一个条件过滤器:
angular.module('myFilters', []).
/**
* "if" filter
* Simple filter useful for conditionally applying CSS classes and decouple
* view from controller
*/
filter('if', function() {
return function(input, value) {
if (typeof(input) === 'string') {
input = [input, ''];
}
return value? input[0] : input[1];
};
});
It takes a single argument, which is either a 2-element array or a string, which gets turned into an array that is appended an empty string as the second element:
它接受一个参数,它是一个 2 元素数组或一个字符串,它被转换为一个数组,并附加一个空字符串作为第二个元素:
<li ng-repeat="item in products | filter:search | orderBy:orderProp |
page:pageNum:pageLength" ng-class="'opened'|if:isOpen(item)">
...
</li>
回答by Joe Steele
If you want to go beyond binary evaluation and keep your CSS out of your controller you can implement a simple filter that evaluates the input against a map object:
如果您想超越二进制评估并将 CSS 排除在控制器之外,您可以实现一个简单的过滤器,该过滤器根据地图对象评估输入:
angular.module('myApp.filters, [])
.filter('switch', function () {
return function (input, map) {
return map[input] || '';
};
});
This allows you to write your markup like this:
这允许您像这样编写标记:
<div ng-class="muppets.star|switch:{'Kermit':'green', 'Miss Piggy': 'pink', 'Animal': 'loud'}">
...
</div>
回答by Pytth
The was I recently did that was doing this:
我最近做的就是这样做:
<input type="password" placeholder="Enter your password"
ng-class="{true: 'form-control isActive', false: 'isNotActive'}[isShowing]">
The isShowing
value is a value that is located on my controller that gets toggled with the click of a button and the parts between the single parenthesis are classes I created in my css file.
该isShowing
值是位于我的控制器上的一个值,通过单击按钮可以切换,单括号之间的部分是我在 css 文件中创建的类。
EDIT: I would also like to add that codeschool.com has a free course that is sponsored by google on AngularJS that goes over all of this stuff and then some. There is no need to pay for anything, just signup for an account and get going! Best of luck to you all!
编辑:我还想补充一点,codeschool.com 有一个免费课程,由谷歌在 AngularJS 上赞助,该课程涵盖了所有这些内容,然后是一些。无需支付任何费用,只需注册一个帐户即可开始使用!祝大家好运!
回答by lionroots
Ternary operator has just beenadded to angular parser in 1.1.5.
三元运算符刚刚在1.1.5 中添加到角度解析器中。
So the simplest way to do this is now :
所以现在最简单的方法是:
ng:class="($index==selectedIndex)? 'selected' : ''"
回答by Lewis Hai
We can make a functionto manage return class with condition
我们可以创建一个函数来管理带条件的返回类
<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) {
switch(strValue) {
case "It is Red":return "Red";break;
case "It is Yellow":return "Yellow";break;
case "It is Blue":return "Blue";break;
case "It is Green":return "Green";break;
case "It is Gray":return "Gray";break;
}
}
}]);
</script>
And then
进而
<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>
You can refer to full code page at ng-class if example
如果示例,您可以参考ng-class 中的完整代码页