<!DOCTYPE html>
<html>
<head>
<script data-require="jquery@*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app='myApp'
ng-controller='PromisesPromisesCtrl'>
<h1>HTML Fetcher</h1>
<button ng-click='addUrl()'>Add...</ng-click>
<button ng-click='executeCalls(urls)'>Go Get Em</button>
<hr/>
<div ng-repeat='url in urls'>
<input type='text' ng-model='url.url'> {{ url.url }} <br/>
</div>
<hr/>
<h2>Logs</h2>
<p ng-repeat='record in log track by $index'>
<span ng-bind='record'></span>
</p>
</body>
</html>
(function() {
'use strict';
angular.module('myApp', [])
.controller('PromisesPromisesCtrl', function($scope, asyncService) {
$scope.log = [
];
$scope.urls = [
{ url: 'ajax1.html'},
{ url: 'ajax2.html'},
{ url: 'ajax3.html'}
];
$scope.addUrl = function() {
$scope.urls.push('http://');
};
$scope.executeCalls = function() {
$scope.log.length = 0;
asyncService.loadDataFromUrls($scope.urls)
.then(
function(data) {
$scope.results = data;
$scope.log.push(Date.now() + ' - SUCCESS = ' + JSON.stringify(data));
},
function(error) {
$scope.log.push(Date.now() + ' - ERROR - calls failed, error is\n\n' + JSON.stringify(error));
},
function(update) {
$scope.log.push(Date.now() + ' - UPDATE - ' + update);
});
};
}).service('asyncService', function($http, $q) {
return {
loadDataFromUrls: function(urls) {
var deferred = $q.defer();
var urlCalls = [];
angular.forEach(urls, function(url) {
urlCalls.push($http.get(url.url));
});
// they may, in fact, all be done, but this
// executes the callbacks in then, once they are
// completely finished.
$q.all(urlCalls)
.then(
function(results) {
deferred.resolve(
JSON.stringify(results))
},
function(errors) {
deferred.reject(errors);
},
function(updates) {
deferred.update(updates);
});
return deferred.promise;
}
};
});
}());
/* Styles go here */
<p>This is one!</p>
<p>This is ajax 2</p>
<p>This is ajax 3</p>