Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
936 views
in Technique[技术] by (71.8m points)

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

<ul>
  <li data-ng-repeat="image in images" data-ng-click="toggle = !toggle" data-ng-init="toggle=false">
      <img data-ng-class="{'active' : toggle}" src="" />
  </li>
</ul>

CSS for 'active' class is from bootstrap.

So toggling works, which is almost where I want it; I would like it similar to active states in navigation links, except in my example it's dealing with images so need to worry about url strings, etc.

I tried emulating this example found here to no avail (I tried the same logic for images): ng-class to highlight active menu item based on ng-repeat. AngularJS

If someone could point me in the right direction, I would greatly appreciate it. :D

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...