AngularJS 与来自两个 JSON 数组的 ID 连接的嵌套 ng-repeat

AngularJS Nested ng-repeat that connects with the ID from two JSON arrays

我正在尝试找到将两个数组连接在一起的最佳方法,我猜是嵌套的 ng-repeat。这是我可用的数据(非常简短的示例);

GameGenre Table
ID    |    Genre
1     |    Action
2     |    First Person Shooter
3     |    Adventure

Game Table
ID    |    IDGenre   |  Name
1     |    1         |  SpiderMan
2     |    1         |  Batman
3     |    2         |  Wolfenstein
4     |    3         |  Just Cause
5     |    3         |  Tomb Raider
6     |    3         |  Indiana jones

所以我正在寻找将两个数组组合在一起的最佳方法(一种方法/快速方法),所以我得到了这个

IDGameGenre 1 Holds: GAMEID1 and GameID2
IDGameGenre 2 Holds: GameID3
IDGameGenre 3 Holds: GameID4, GameID5, GAMEID6

这是我到目前为止的想法,我首先使用了两个数组:

在控制器中:

 $http({
     method: 'Get',
     url: http://URL/api/GameGenre/All"
 })
     .success(function (data) {
          $scope.GameGenre= data;
     });

 $http({
     method: 'Get',
     url: http://URL/api/Game/All"
 })
     .success(function (data) {
          $scope.Game= data;
     });

 $scope.getTheGame = function(ID) {
     return Game.get({IDGenre: ID});
 };

在HTML

<div class="listing" ng-repeat="Genre in GameGenre" ng-init='getTheGame(Genre.ID)'>
       <div class="Game" ng-repeat="Game in getTheGame"></div>
</div>

但我似乎无法完成这两项工作,我如何能够首先使用这两个数组,将它们都添加到一个范围,然后对信息进行排序。

首先,您的 $http 请求是异步的。您需要将它们链接起来,或者同步解析,这可以通过 $q.all() 来完成。然后,一旦解析并填充到数组中,您就可以操作它们并为您的 table 创建一个新数组。我发现 2 个 for 循环是最简单的方法(祝你好运,用 .map/.reduce/等缩短它)。

这是一个静态示例:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http, $q) {
  /*
  var GGpromise = $http(...).then(function (res) {
    return res.data;
  });
  var Gpromise = $http(...).then(function (res) {
    return res.data;
  });
    
  $q.all([GGpromise, Gpromise]).then(function(res){
    var GG = res...;
    var G = res...;
  }).finally(function(){
    // main code here:
    // ...
  })
  */
  
  var GG = [
    {"ID":1,"Genre":"Action"},
    {"ID":2,"Genre":"First Person Shooter"},
    {"ID":3,"Genre":"Adventure"}
  ];
  var G = [
    {"ID":1,"IDGenre":1,"Name":"Spider Man"},
    {"ID":2,"IDGenre":1,"Name":"Batman"},
    {"ID":3,"IDGenre":2,"Name":"Wolfenstein"},
    {"ID":4,"IDGenre":3,"Name":"Just Cause"},
    {"ID":5,"IDGenre":3,"Name":"Tomb Raider"},
    {"ID":6,"IDGenre":3,"Name":"Indiana Jones"}
  ];

  $scope.games = [];
  for (var i = 0; i < GG.length; i++) {
    var temp = {};
    temp.IDGameGenre = GG[i].ID;
    temp.Holds = [];
    for (var j = 0; j < G.length; j++) {
      if (GG[i].ID == G[j].IDGenre) {
        temp.Holds.push(G[j].ID);
      }
    }
    $scope.games.push(temp);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <pre>{{games | json}}</pre>
</div>

或者您可以尝试类似的操作:-

<ul>
    <li ng-repeat="Genre in GameGenre">{{ Genre.Name }}</li>
    <ul>
        <li ng-repeat="Game in GameArray" ng-if="Game.GenreId == Genre.Id">{{ Game.Name }}</li>
    </ul>
</ul>