假设你有一个在ul中呈现的数组,每个元素都有一个li,控制器上有一个名为selectedIndex的属性。在AngularJS中,用索引selectedIndex向li中添加类的最好方法是什么?
我目前复制(手工)li代码,并将类添加到li标记之一,并使用ng-show和ng-hide只显示每个索引一个li。
假设你有一个在ul中呈现的数组,每个元素都有一个li,控制器上有一个名为selectedIndex的属性。在AngularJS中,用索引selectedIndex向li中添加类的最好方法是什么?
我目前复制(手工)li代码,并将类添加到li标记之一,并使用ng-show和ng-hide只显示每个索引一个li。
当前回答
如果你想超越二进制计算,让你的CSS远离你的控制器,你可以实现一个简单的过滤器,根据map对象计算输入:
angular.module('myApp.filters, [])
.filter('switch', function () {
return function (input, map) {
return map[input] || '';
};
});
这允许你像这样写你的标记:
<div ng-class="muppets.star|switch:{'Kermit':'green', 'Miss Piggy': 'pink', 'Animal': 'loud'}">
...
</div>
其他回答
如果你有一个应用于很多元素的公共类,你可以创建一个自定义指令来添加这个类,比如ng-show/ng-hide。
这个指令会在按钮被点击时添加类'active'
module.directive('ngActive', ['$animate', function($animate) {
return function(scope, element, attr) {
scope.$watch(attr.ngActive, function ngActiveWatchAction(value){
$animate[value ? 'addClass' : 'removeClass'](element, 'active');
});
};
}]);
更多信息
这里有一个更简单的解决方案:
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>
只是添加了一些对我来说有用的东西,经过大量的搜索……
<div class="form-group" ng-class="{true: 'has-error'}[ctrl.submitted && myForm.myField.$error.required]">
希望这有助于您的成功开发。
=)
无文档的表达式语法:伟大的网站链接…=)
如果你正在使用angular pre v1.1.5(即没有三元操作符),并且你仍然想要在这两种情况下使用等效的方法来设置值,你可以这样做:
ng-class="{'class1':item.isReadOnly == false, 'class2':item.isReadOnly == true}"
如果你不想像我一样把CSS类名放在控制器中,这里有一个我从v1时代以前就使用的老技巧。我们可以编写一个表达式,直接计算所选的类名,不需要自定义指令:
ng:class="{true:'selected', false:''}[$index==selectedIndex]"
请注意使用冒号的旧语法。
还有一种新的更好的有条件地应用职业的方法,比如:
ng-class="{selected: $index==selectedIndex}"
Angular现在支持返回对象的表达式。该对象的每个属性(名称)现在都被视为一个类名,并根据其值应用。
然而,这些方式在功能上并不相等。这里有一个例子:
ng-class="{admin:'enabled', moderator:'disabled', '':'hidden'}[user.role]"
因此,我们可以通过将模型属性映射到类名来重用现有的CSS类,同时将CSS类排除在Controller代码之外。