AngularJs – Best-Practices on adding an active class on click (ng-repeat)

The best solution would be to target it via angulars $index which is the objects index/position in the array;

HTML

<div ng-app='app' class="filters_ct" ng-controller="selectFilter">
    <ul>
        <li ng-repeat="filter in filters" ng-click="select($index)" ng-class="{sel: $index == selected}">
            <span class="filters_ct_status"></span>
            {{filter.time}}
        </li>
    </ul>
</div>

JS/Controller

var app = angular.module('app', []); 

app.controller('selectFilter', function($scope) {
var filters = [
            {
                'filterId': 1,
                'time': 'last 24 hours',
            },
            {
                'filterId': 2,
                'time': 'all',
            },
            {
                'filterId': 3,
                'time': 'last hour',
            },
            {
                'filterId': 4,
                'time': 'today',
            },
            {
                'filterId': 5,
                'time': 'yersteday',
            }
        ]; 

    $scope.filters = filters;
    $scope.selected = 0;

    $scope.select= function(index) {
       $scope.selected = index; 
    };
});

JSFIDDLE

Leave a Comment