javascript - 调整 ng-repeat 以匹配对象结构

标签 javascript angularjs angularjs-ng-repeat

我有一个看起来像这样的对象:

 $scope.hobbies = {
    list: [
      {
        "PersonId": 23,
        "PersonName": "John Smith",
        "Hobbies": [
          {
            "HobbyTitle": "Paragliding",
            "HobbyId": 23
          },
          {
            "HobbyTitle": "Sharking",
            "HobbyId": 99
          }
        ]
      }             
    ]
   };

我正在尝试开发一种 View ,允许用户选择每个人的爱好。

我有一个笨蛋here

我的问题是所有选定的爱好都显示在每个人的下面。这是因为我只是将所有选定的爱好推送到 selectedHobbies 数组。

  $scope.addHobbyItem = function (item) {
    var index = $scope.selectedHobbies.list.indexOf(item);
    if (index === -1) {
      $scope.selectedHobbies.list.push(item);
    }
  };

这当然行不通,因为一旦选择了一个爱好,它就会显示在每个人的下面。我如何调整代码以适应我对 selectedHobbies 进行 ng-repeating 的方式?

HTML 如下。我还使用指令来监听爱好容器上的点击并触发 addHobbyItem()

<div data-ng-repeat="personHobby in hobbies.list">
  <div>
    <div style="border: 1px solid black; margin: 10px 0 10px">
      <strong>{{ personHobby.PersonName }}</strong>
    </div>
  </div>
  <div class="">
    <div class="row">
      <div class="col-xs-6">
        <div data-ng-repeat="hobby in personHobby.Hobbies" data-ng-if="!hobby.selected">
          <div data-hobby-item="" data-selected-list="false" data-ng-class="{ selected : hobby.selected }"></div>
        </div>
      </div>
      <div class="col-xs-6">
        <div data-ng-repeat="hobby in selectedHobbies.list">
          <div data-hobby-item="" data-selected-list="true"></div>
        </div>
      </div>
    </div>
  </div>
</div>

最佳答案

你的selectedHobbies应该是一个 map ,其中的键是人的id,值是他选择的爱好的列表。 checkout this plunker

  $scope.selectedHobbies = {
    map: {}
  };

  // Add a hobby to our selected items
  $scope.addHobbyItem = function(pid, item) {
    if(!$scope.selectedHobbies.map[pid]) {
      $scope.selectedHobbies.map[pid] = [];
    }
    var index = $scope.selectedHobbies.map[pid].indexOf(item);
    if (index === -1) {
      $scope.selectedHobbies.map[pid].push(item);
    }
  };

在指令中使用人员 ID 调用 addHobbyItem

scope.addHobbyItem(scope.personHobby.PersonId, scope.hobby);

最后在 html 中迭代每个人选择的爱好

    <div data-ng-repeat="hobby in selectedHobbies.map[personHobby.PersonId]">
      <div data-hobby-item="" class="add-remove-container--offence" data-selected-list="true"></div>
    </div>

关于javascript - 调整 ng-repeat 以匹配对象结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26516738/

相关文章:

javascript - 无法在嵌套的 ngRepeat 上触发动画

angularjs - Ng-Select 在 Ng-Select 中从第一个选择框中选择下一个值

javascript - 从 Q promise 中崩溃应用程序而不是通过一系列 promise 传播拒绝?

javascript - 循环中$index的值

javascript - 使用路由在 AngularJS 应用程序中进行数据绑定(bind)

javascript - 无法访问 $watch 内的范围变量

javascript - ng-table 从范围中过滤串联值

javascript - 每 20 像素更改 img 源

javascript - gadicc/meteor-reactive-window Meteor 包的预期空间错误问题

javascript - 在数据表上实现服务器端分页