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

时间:2014-10-22 20:42:17

标签: javascript angularjs angularjs-ng-repeat ng-repeat

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

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

我正在尝试开发一个视图,让用户可以选择每个人的爱好。

我有一个羽毛here

我的问题是所有选定的爱好都会显示在每个人的下方。这是因为我只是将所有选定的爱好推向选定的爱好阵列。

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

这当然不起作用,因为一旦选择了一个爱好,它就会显示在每个人的下方。我怎样才能调整代码以便按照我对所选爱情重复的方式进行操作?

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>

2 个答案:

答案 0 :(得分:2)

您选择的爱好应该是一个地图,其中键是人员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);
    }
  };

在指令中使用person 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>

答案 1 :(得分:0)

类似的东西:

http://plnkr.co/edit/7BtzfCQNTCb9yYkv1uPN?p=preview

我使用$ parent。$ index创建一个包含每个人兴趣爱好的数组数组。

 $scope.addHobbyItem = function (item, index) {

     var ine = $scope.selectedHobbies[index].indexOf(item);
     if (ine === -1) {
        $scope.selectedHobbies[index].push(item);
     }
 };

 function hobbyClickEvent() {
    if (!$(element).hasClass('selected')) {

      scope.addHobbyItem(scope.hobby, scope.$parent.$index);
    } else {
      scope.removeHobbyItem(scope.hobby);
    }
  }

并在HTML中:

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