简体   繁体   English

用AngularJS添加到json对象

[英]Adding into json object with AngularJS

Let's say I have a animals.json file with the following content: 假设我有一个具有以下内容的animals.json文件:

{
  "animals": {
    "elephant": {
      "size": "large"
    },
    "mouse": {
        "size": "small"
    }
  }
}

And I'm adding that data to the scope of my controller: 我将这些数据添加到控制器的范围内:

animalsApp.controller('animalsCtrl', function($scope, $http){
    $http.get('../../animals.json').success(function(data){
        $scope.animals = data.animals;
    });
});

Which works perfectly, however let's say I need to get some data from an API that I need to add to $scope.animals, which has the following data: 效果很好,但是,我们需要从需要添加到$ scope.animals的API中获取一些数据,该数据具有以下数据:

{
    "animal_name": "Leonardo"
}

Which is returned when I go to the api with the jsons data: 当我使用jsons数据转到api时返回的结果:

http://api.someapi.com/animals/{animals.elepahant} // returns above json

Pretend {animals.elaphant} is the results I get when i loop my json, get a value from it, and get the data from a remote api with the query being a variable of mines, add results to my json and return that new modified json in $scope.animals. 假装{animals.elaphant}是当我循环json,从中获取值并从远程api获取数据时得到的结果,查询是我的变量,将结果添加到json并返回新修改的结果$ scope.animals中的json。

So the final json would look like: 所以最终的json看起来像:

{
  "animals": {
    "elephant": {
      "size": "large",
      "name": "Leonardo"
    },
    "mouse": {
        "size": "small",
        "name": "Vader"
    }
  }
}

How can I achieve this? 我该如何实现?

Normally you would have an array of animals and loop through that array. 通常,您将有一个animals数组并遍历该数组。

Since you have an object the principle is the same. 由于您有一个对象,原理是相同的。 It is important to use a closure for the loop. 对循环使用closure很重要。 Will use angular.forEach() to create that closure. 将使用angular.forEach()创建该闭包。

Using for loops by themselves do not create a closure and can be problematic since the loop finishes long before the request responses are returned 单独使用for循环不会创建闭包,并且可能会出现问题,因为循环在返回请求响应之前很长时间就已结束

$http.get('../../animals.json').success(function(data){
    $scope.animals = data.animals;
    angular.forEach(data.animals, function(v, animal_type){
       var url = 'http://api.someapi.com/animals/' + animal_type; 
       $http.get(url).success(function(resp){
           v.name = resp.animal_name;
       });
    });
});

There are also alternative ways to write this using chained promises. 还有其他方法可以使用链式承诺来编写此内容。 I kept it simple for now 我暂时保持简单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM