I need to update the data for each object in an array using a for loop and once all the data is captured, run a function. I don't want to mix jQuery in this and do it the proper Angular way of doing
Here is what I am doing,
$scope.units = ['u1', 'u2', 'u3'];
$scope.data = null;
//get individual unit data
$scope.getUnitData = function(unit){
service.getUnitData(unit).success(function(response){
$scope.data.push({'id' : response.id , 'value' : response.value});
});
};
$scope.updateAllUnits = function(){
$scope.data = null ; //remove existing data
angular.forEach($scope.units,function(val,key){
$scope.getUnitData(val);
};
console.log($scope.data); // Need to show all the data but currently it does not as the for each loop didn't complete
};
The service is defined as.
app.factory('service',function($http){
return {
getUnitData : function(unit){
return $http({
url : myURL,
method : 'GET',
params : {'unit' : unit}
});
}
}
});
How do I receive a callback when all the pulling has been done in the for loop ?
The result of your $http(...)
call is a promise. This means you can use $q.all
to wait for an array of them to complete.
$scope.updateAllUnits = function(){
$scope.data = null ; //remove existing data
var promises = [];
angular.forEach($scope.units,function(val,key){
promises.push($scope.getUnitData(val));
});
$q.all(promises).then(function success(data){
console.log($scope.data); // Should all be here
}, function failure(err){
// Can handle this is we want
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With