2 Json文档关联并嵌套在angularJS中

时间:2016-07-08 00:06:11

标签: javascript angularjs

我有两个json。例如

1

[ {"id":"23", "name":"mehmet"} , {"id":"22", "name":"jack"} ]

2

[ {"id":"1", "userID":"23"} , {"id":"2", "userID":"23"}, {"id":"3", "userID":"22"}]

在第一个json mehmet中有2个条目第二个json(关联用户ID)

我想......

mehmet (source first json)
     id:1   (second json)
     id:2   (second json)

jack(source first json)
    id:3 (second json)

我的控制器:

.controller('ListviewCtrl', function($scope, $http, SERVER) {

  $scope.topics = [];
  function loadTopics(params, callback){
      $http.get(SERVER.url+'/listtopic', {params: params})
      .success(function(response){
        var topics = [];

        angular.forEach(response, function(result){


          topics.push(result);
        });

        callback(topics);
      });
    };



      $scope.tweetler = [];
  function loadTweetler(params, callback){
      $http.get(SERVER.url+'/tweet')
      .success(function(response){
        var tweetler = [];

        angular.forEach(response, function(result){
          tweetler.push(result);
        });
        callback(tweetler);
      });
    };

如何使用ng-repeat和list associate 2 json?

2 个答案:

答案 0 :(得分:0)

将其中一个数组添加到对象中,然后更容易从中获取数据。为了简单起见,采用1:1关系数组..

var users = [
  {"id":"1", "name":"mehmet"},
  {"id":"2", "name":"jack"}
]

// This is simple 1:1 relationship.. ID:NAME
{
  "1": "mehmet",
  "2": "jack"
}

// To do it, is very simple
$scope.users = {};
angular.forEach(users, function(user) { $scope.users[user.id] = user.name})

然后您可以通过ID

获取正确的用户
<li ng-repeat="post in posts">
   <span>Author: {{users[post.userId]}}</span>
</li>

答案 1 :(得分:0)

您可以在 ng-repeat内创建过滤器,如下所示:

&#13;
&#13;
var app = angular.module('app', []);

app.controller('mainCtrl', function($scope) {
  $scope.parents = [  
     {  
        "id":23,
        "name":"mehmet"
     },
     {  
        "id":22,
        "name":"jack"
     }
  ];

  $scope.childs = [  
     {  
        "id":1,
        "userID":23
     },
     {  
        "id":2,
        "userID":23
     },
     {  
        "id":3,
        "userID":22
     }
  ];
});
&#13;
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <ul>
    <li ng-repeat-start="parent in parents" ng-bind="parent.name"></li>
    <ul ng-repeat-end ng-repeat="child in childs | filter: { userID: parent.id }">
      <li ng-bind="'Id:' + child.id"></li>
    </ul>
  </ul>
</body>

</html>
&#13;
&#13;
&#13;