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

后端 未结 4 2141
一个人的身影
一个人的身影 2020-12-02 12:32

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 :



        
4条回答
  •  忘掉有多难
    2020-12-02 12:52

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

    HTML

    • {{filter.time}}

    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

提交回复
热议问题