AngularJS Promises - $q.all()
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-controller="MyCtrl">2 x 100 = {{myValue}}</div>
JavaScript
var myApp = angular.module('myApp', []);
function MyCtrl($scope, $q, $timeout) {
// This function will return the argument multiplied
// by 100 after waiting for two seconds. This is to
// demonstrate an asychronous activity.
function getValue(num){
var deferred = $q.defer();
$timeout(function(){
deferred.resolve(num * 100);
},2000);
// Return the promise to allow other code to act
// on the result.
return deferred.promise;
}
// Let's get a promise for calculating the value of
// 2 x 100
var getMyValue = getValue(2);
// Once the code is finished calculating, specify
// a function to execute with the returned value
getMyValue.then(function(val) {
$scope.myValue = val;
});
}