单击时更改ng类(嵌套ng重复)

Changing ng-class when clicked (nested ng-repeat)

本文关键字:ng 嵌套 重复 单击      更新时间:2023-09-26

这是我的角度代码。。(描述我遇到的问题是,按钮重复的嵌套ng重复是列出的所有"作业"的行为(单击时)。。

    <div class="row" ng-repeat="job in jobs">
        <div class="btn-group btn-group-justified" role="group">
             <div class="btn-group" role="group" ng-repeat="status in job.statuscollection">
                   <button type="button" class="btn btn-default" ng-class="{ 'btn-info': $index == selectedIndex }" ng-click="itemClicked($index)">{{status.name}}</button>
             </div>
        </div>
    </div>

这是我的js代码。。

    $scope.jobs = [
    {
        _id: new Date().toISOString(),
        statuscollection: [
            { name: "Off-Site"},
            { name: "Enroute" },
            { name: "On-Site" },
        ]
        docType: "job",
    },
    {
        _id: new Date().toISOString(),
        statuscollection: [
            { name: "Off-Site"},
            { name: "Enroute" },
            { name: "On-Site" },
        ]
        docType: "job",
    }];

这是我的ng点击功能。。

    $scope.itemClicked = function ($index) {
         $scope.selectedIndex = $index;
         console.log($scope.jobs[$index]);
    }

我有不止一个作业,我在代码中只包含了一个,以减少它的数量。但当浏览器以正确的方式生成这些数据时,单击"作业"按钮之一对每个作业都会做同样的事情。

这意味着,如果我点击一个作业的"现场"按钮,则所有作业都会重复。。我如何才能使单击作业的一个按钮只对该作业有效,而不是全部有效?

跟踪多个ngRepeats索引的正确Angular方法是使用ngInit创建一个局部变量,为ngRepeat的每个实例别名$index。通常不鼓励使用$parent来获取其$index位置。

在下面的例子中,我们有两个ngRepeats,因此有两个别名索引变量:outerIndexinnerIndex:

  <tbody ng-repeat="country in countries" ng-init="outerIndex = $index">
    <tr ng-repeat="city in country.cities" ng-init="innerIndex = $index">
      <td>{{city}}</td>
      <td>{{country.name}}</td>
      <td>({{outerIndex}}, {{innerIndex}})</td>
    </tr>
  </tbody>

Plunker:http://plnkr.co/edit/VA1XWWrG3pghEcWli06F


最终编辑

在对问题背后的上下文有了更多的了解之后,实际上OP在所选对象上设置isActive属性,而不是试图跟踪和匹配索引,这更有意义。也就是说,上述方法仍然有效并且适用于跟踪多个ngRepeats 上的索引

 $scope.itemClicked = function (status, job) {
   if (status.isActive) {
     status.isActive = false;
   } else {
     angular.forEach(job.statuscollection, function(status) {
       status.isActive = false;
     });
     status.isActive = true;
   }
 }

更新的plunker:http://plnkr.co/edit/v70fY30PjoTXCrhOPVZB

使用$parent.$index而不是$index来指代外部ng重复循环(即作业循环):

<button type="button" class="btn btn-default" ng-class="{ 'btn-info': $parent.index == selectedIndex }" ng-click="itemClicked($parent.$index)">{{status.name}}</button>

$index是内部循环的索引。

$parent.$index是外循环的索引。