Search code examples
javascriptangularjsangularjs-ng-repeatng-options

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>
</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";
            }
        }      

    }]);

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

["2","3"]

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?


Solution

  • 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}">