AngularJs - 最佳实践上添加上点击一个活动类(NG-重复)

问题描述:

我要在名单上点击添加活动类,我尝试以下code,但它增加了对我的所有项目活动类:/:

I want to add an active class on click in a list, i tried the following code, but it adds the active class on all my items :/ :

HTML:

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

JS:

  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',
            }
        ]; 


function selectFilter($scope) {

    $scope.items = ['filters'];
    $scope.selected = $scope.items[0];

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

}

请,给我一些帮助。

感谢

最好的解决办法是通过angulars目标为 $指数这是在对象的索引/位置数组;

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 /控制器

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

JSFIDDLE