How do you toggle an active state ng-class in an ng-repeat item using ng-click?

前端 未结 2 1132
闹比i
闹比i 2020-12-16 04:38
相关标签:
2条回答
  • 2020-12-16 05:11

    You can try it in following way:

    <body>
    <style>
    .blue{
        background:blue;
    }
    </style>
    <div ng-app='my'>
      <div ng-controller='maincontroller as mainctrl'> 
        <div ng-repeat='item in mainctrl.arr'>
        <p ng-class='{"blue":mainctrl.bgcolor==item}'
        ng-click='mainctrl.addColor(item)'>
        item {{item}}
        </p>
    
        </div>
      </div>
    </div>
    <script>
    var app = angular.module('my',[])
    app.controller('maincontroller',maincontroller)
    function maincontroller(){
    var mainctrl = this;
    mainctrl.arr = [1,2,3,4,5,6];
    
    mainctrl.addColor = function(data){
    mainctrl.bgcolor = data
    }
    }
    </script>
    </body>
    
    0 讨论(0)
  • 2020-12-16 05:14

    What i would do in your situation is define an object inside the parent scope of that ng-repeat, and assign the index or whatever you wish to a propperty of that object. That is because objects work by reference in javascript, which means that the ng-click will actually update the parent scope attribute instead of redefine it. Example at plnkr: http://plnkr.co/edit/oA12yLIb3RnlSYe6JxhI?p=preview

    <!DOCTYPE html>
    <html ng-app>
    
      <head>
        <style>
            .active{
                background-color: red;
                height: 500px;
                width: 500px;
            }
        </style>
      </head>
    
      <body ng-controller="HolaCtrl">
        <ul>
          <li data-ng-repeat="image in images" data-ng-click="toggleObject.item = $index">a
             <img data-ng-class="{'active' : toggleObject.item == $index}" src="" /><br>
          </li>
        </ul>
        <script>
            function HolaCtrl($scope){
                $scope.images = [1,2,3];
                $scope.toggleObject = {item: -1};
            }
        </script>
      </body>
    
    </html>
    

    Cheers

    0 讨论(0)
提交回复
热议问题