我有一个使用ng-options的选择。所选的值使用过滤器填充ng-repeat列表。现在我需要为一些ng-repeat列表项添加一个类。我有一个列表元素的id,要在类中添加类。
Html代码:
<select class="form-control" ng-options="car.BaseStation as car.BaseStation for car in UnUsedCars | unique: 'BaseStation' | orderBy:'BaseStation'" ng-model="selected.BaseStation" ng-change="locationChanged()">
<option value="">All Locations</option>
</select>
<h3>Select Car</h3>
<ul class="cablist">
<li ng-repeat="unUsedCar in UnUsedCars | filter: selected.BaseStation" id="{{unUsedCar.Id}}">
<div class="cardetails">
<h4>{{unUsedCar.CarType}}</h4>
</div>
</li>
</ul>
JS
<script data-require="angular-ui@*" data-semver="0.4.0" src="http://rawgithub.com/angular-ui/angular-ui/master/build/angular-ui.js"></script>
<script type="text/javascript">
var carApp = angular.module('carApp', ['ui.directives','ui.filters']);
carApp.controller('CarCtrl', ['$scope', function(scope) {
scope.locationChanged = function() {
arrayLength = scope.carArray.length; //scope.carArray is the array of li element Id on which class "selected" is to be added.
for(i = 0; i < arrayLength; i++) {
var carId = scope.carArray[i];
document.getElementById(carId).className += " selected";
}
}
}]);
数据数组示例
[{
"Id" : "1",
"CarType" : "Audi",
"BaseStation" : "Canada"
},
{
"Id" : "2",
"CarType" : "BMW",
"BaseStation" : "U.S.A"
},
{
"Id" : "3",
"CarType" : "Benz",
"BaseStation" : "Canada"
}]
scope.carArray数据示例
["2","3"]
当我从带有ng-options的select中选择另一个位置时,我的js假设将“selected”类添加到li项目中,其中的id在scope.carArray中。它有时会起作用,但大多数时候都会崩溃。我在这里犯了什么错误?
答案 0 :(得分:1)
不要通过javascript手动添加类名,而是使用Angular的ngClass
指令。
<li ng-repeat="unUsedCar in UnUsedCars | filter: selected.BaseStation" id="{{unUsedCar.Id}}"
ng-class="{selected: carArray.indexOf(unUsedCar.Id) > -1}">