I'm building an AngularJS app (using 1.2.0 RC1) that uses a REST API for saving data that the user has entered. The user will enter data about a company and it consists of two core components that I need to save:
- The company details
- Contacts within that company
I have 1 REST method to call to save the company and then I have another that I call for each contact to be saved.
I planned to use $q
to track all the requests and resolve them once it's completed.
The problem I've hit is that although the REST API is being called successfully and all my data is being saved my controller isn't being notified when all the promises have resolved until I click a button on the screen, such as the add contact
button. I've tried eliminating the REST API as a source of problems but it still happens when simulating delayed jobs using setTimeout
.
Here's my service
module:
angular.module('myApp', ['restService'])
.factory('service', ['client', '$q', function (client, $q) {
return {
create: function (name, people) {
var deferred = $q.defer();
setTimeout(function () {
console.log('saved company ' + name);
var promises = people.map(function (person) {
var dfd = $q.defer();
setTimeout(function () {
console.dir(person);
console.log('Person saved');
dfd.resolve();
}, 100);
return dfd.promise;
});
$q.all(promises).then(deferred.resolve);
}, 100);
return deferred.promise;
}
};
}]);
And here's my controller:
angular.module('club', ['myApp'])
.controller('RegisterCtrl', ['$scope', 'service', function ($scope, service) {
$scope.addPerson = function () {
$scope.company.people.push({
firstName: '',
lastName: '',
email: ''
});
};
$scope.removePerson = function (person, index) {
$scope.company.people.splice(index, 1);
};
$scope.save = function (company) {
service.createClub(company.name, company.people).then(function () {
console.log('And we\'re done');
});
};
$scope.company = {
name: '',
people: []
};
}]);
So when I invoke the save
method (which is ng-click
bound to a button) I will have a console.log set like this:
saved company
Object
Person saved
Object
Person saved
Notice there's no And we're done
output. As soon as I click the button that addPerson
is ng-click
bound to I get the final message output.