Arjun Ajith Arjun Ajith - 1 year ago 71
AngularJS Question

Dynamically allocating class to ng-repeat items with ng-options select

I have a select which uses ng-options. The selected value of this populates a ng-repeat list using filter. Now I need to add a class to some of the ng-repeat list items. I have the 'id's of the list elements, to which the class is to be added, in an array.

Html Code:

<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>

<h3>Select Car</h3>
<ul class="cablist">
<li ng-repeat="unUsedCar in UnUsedCars | filter: selected.BaseStation" id="{{unUsedCar.Id}}">
<div class="cardetails">


<script data-require="angular-ui@*" data-semver="0.4.0" src=""></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";


Example of data array

"Id" : "1",
"CarType" : "Audi",
"BaseStation" : "Canada"
"Id" : "2",
"CarType" : "BMW",
"BaseStation" : "U.S.A"
"Id" : "3",
"CarType" : "Benz",
"BaseStation" : "Canada"

scope.carArray data example


When I choose another location from select with ng-options my js is suppose to add class "selected" to the li items, which has their ids in scope.carArray. It some times works, but most times it crashes. What are the mistakes I made here?

Answer Source

Instead of adding the classname manually through javascript, use Angular's ngClass directive.

<li ng-repeat="unUsedCar in UnUsedCars | filter: selected.BaseStation" id="{{unUsedCar.Id}}" 
    ng-class="{selected: carArray.indexOf(unUsedCar.Id) > -1}">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download