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

后端 未结 4 2128
一个人的身影
一个人的身影 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 13:11

    Slow to answer, here is what I got ( might add a little more )

    WORKING DEMO : http://jsfiddle.net/WVY7L/

    TEMPLATE

    • {{filter.time}}

    CONTROLLER

    $scope.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.selectedIndex = 0; /* first one set active by default */
    $scope.select= function(i) {
      $scope.selectedIndex=i;
    };
    
    • worth a mention that in the data you have trailing comma that should not be there.

       { filterId: 1, time: 'last 24 hours'**,**}
      

    The rest was ensuring your controller was being passed the array number

    ng-click="select($index)" ng-class="{active: $index===selectedIndex}"
    

    and being able to save that array number selectedIndex for use in your template

    $scope.selectedIndex
    

    ng-class syntax

        {active: $index===selectedIndex}
    

    Translates to add class with name of 'active' when the '$index' is equal to the 'selectedIndex'

提交回复
热议问题