你如何在NG-重复使用项目切换活动状态纳克级的NG-点击?

问题描述:

<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的'积极'类是引导。搜索结果
因此切换的作品,这几乎是我想要它;我想它类似于导航链接激活状态,除了在我的例子它在处理图像,以便无需担心URL字符串,等等。

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.

我试图仿效这个例子在这里找到无济于事(我试过图像相同的逻辑):ng-class基于NG-重复高亮活动菜单项。 AngularJS

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

如果有人能指出我在正确的方向,我将不胜AP preciate它。 :D

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

我会在你的情况做的是定义一个对象,NG-重复父范围内,并指定你想索引或什么来的propperty该对象。这是因为对象引用在JavaScript中工作,这意味着NG-点击,实际上会更新父作用域属性,而不是重新定义它。
例如在plnkr:http://plnkr.co/edit/oA12yLIb3RnlSYe6JxhI?p=$p$pview

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>

干杯