user254799
user254799

Reputation: 75

Adding into json object with AngularJS

Let's say I have a animals.json file with the following content:

{
  "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:

{
    "animal_name": "Leonardo"
}

Which is returned when I go to the api with the jsons data:

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.

So the final json would look like:

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

How can I achieve this?

Upvotes: 1

Views: 683

Answers (1)

charlietfl
charlietfl

Reputation: 171690

Normally you would have an array of animals and loop through that array.

Since you have an object the principle is the same. It is important to use a closure for the loop. Will use angular.forEach() to create that closure.

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

$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

Upvotes: 1

Related Questions