search

Home  >  Q&A  >  body text

angular.js - How to use instructions to dynamically switch classes in a list in angular

代码

The desired effect is to add a style to the currently clicked one and clear the others.

天蓬老师天蓬老师2824 days ago520

reply all(2)I'll reply

  • 某草草

    某草草2017-05-15 17:04:38

    Don’t go to such trouble, let’s just use ng-class, like this:

    Correction:

    Okay, I was wrong

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body ng-app="myApp" ng-controller="myCtrl">
        <ul>
            <li ng-repeat="x in ulList" ng-class="{active: currentIndex === $index}" ng-click="handleActive($index)">{{ x.li }}</li>
        </ul>
        <script type="text/javascript">
            var app = angular.module('myApp', []);
            app.controller('myCtrl', ['$scope', function($scope){
                $scope.handleActive = function(index){
                  $scope.currentIndex = index;
                };
                
                $scope.ulList = [
                    {
                        id: '1',
                        li: '01'
                    },{
                        id: '2',
                        li: '02'
                    },{
                        id: '3',
                        li: '03'
                    },{
                        id: '4',
                        li: '04'
                    }
                ];
            }]);
        </script>
    </body>
    </html>

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-15 17:04:38

    Use attribute binding
    Add an isSelected attribute to each element in ulList, and change the value of isSelected when Clicked
    Use ng-class in HTML

    reply
    0
  • Cancelreply