1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.