angular.forEach and objects angular.forEach and objects angularjs angularjs

angular.forEach and objects


Something like this?

var promises = [];angular.forEach(array, function(index) {  promises.push(Resource.query(...));});$q.all(promises).then(function(result1, result2, result3 ...) {  // do stuff with result1, result2 ... or  // var results = Array.prototype.slice.call(arguments);});


Angular documentation has very good example for this

var values = {name: 'misko', gender: 'male'};var log = [];angular.forEach(values, function(value, key) {    this.push(key + ': ' + value); }, log);


.query returns an array reference which is being filled with data when the xhr is completed.Since, probably id is a unique identifier, the query will return array with a single element, thats why I would suggest you to use .get instead.

Anyway, if you still intent to use .query you can do something like:

var arrays = [];angular.forEach(array, function(index){    arrays.push(Resource.query({id:index}, function(result){        console.log(result)        // returns the expected object,         // but, as expected, I can't access the object outside the async call    }));    console.log(result);    // result is undefined});$scope.$watch(function () {    return arrays;}, function (arrays) {    angular.forEach(arrays, function (array) {       angular.forEach(array[0], function () {          //Do something with the object fields       });    });});

As you can see the code looks pretty bad...

In order to achieve better result you can use:

var objects = [];angular.forEach(array, function(index){    objects.push(Resource.get({ id:index });});$scope.$watch(function () {    return objects;}, function (objects) {    angular.forEach(objects, function (obj) {       angular.forEach(obj, function () {          //Do something with the object fields       });    });});

Even better will be if you let AngularJS to do the $watch by assigning objects to a $scope property.