I've figured out how to share data between two AngularJS controllers using a shared service in the contrived example below:
(Functioning fiddle)
var app = angular.module('myApp', []);
app.factory('UserData', function() {
var data = {foo: 'bar'};
return {
getData: function() {
console.log('getData');
return data;
},
setData: function(newData) {
data = newData;
}
};
});
function MainCtrl($scope, UserData) {
console.log('MainCtrl');
console.log(UserData.getData());
}
MainCtrl.$inject = ['$scope', 'UserData'];
function JobListCtrl($scope, UserData) {
console.log('JobListCtrl');
console.log(UserData.getData());
}
JobListCtrl.$inject = ['$scope', 'UserData'];
My issue is that I would like the data held in UserData to come from an Ajax call (presumably using $http).
I tried doing the Ajax call in the UserData factory function but, since it's running asynchronously, MainCtrl and JobListCtrl are executed before the UserData service actually has any data in it.
Can someone give me some direction about how to set that up?