Angularjs Promise Demo
Well this works fine in 1.x.x but fails to bind values to template in 2.x.x
by Bhavin Surela
HTML
<h2>My App</h2>
<div ng-app="MyApp">
<div ng-controller="MyCtrl">
<div ng-repeat="h in homes">{{h}}</div>
</div>
</div>
JavaScript
var MyApp = angular.module('MyApp', []);
MyApp.controller('MyCtrl', function ($scope, SimpleService,$q) {
var promises=[];
var homes =[];
for(var i =0;i<10;i++){
promises.push(SimpleService.get());
}
var i =0, breakit = false;
while(!breakit){
promises[i].then(function(data){
console.log(i, data);
homes.push(data);
if(i==10){
breakit = true;
}else{
i++;
}
})
}
alert('all calls completed syncronously');
});
angular.module('MyApp')
.factory('SimpleService', ['$q', '$rootScope', function ($q, $rootScope, $timeout) {
var SS = {
get: function () {
var waitTime = Math.floor((Math.random() * 1000) + 1);
var result = Math.floor((Math.random() * 10) + 1);
var d = $q.defer();
setTimeout(function () {
d.resolve(result);
$rootScope.$apply();
}, waitTime)
return d.promise;
}
}
return SS;
}]);