Reputation: 9860
I'm making a web app in angular that is primarily driven with data from remote json objects. I want to load the page with sensible default data, then request the json objects and update the controllers with this new data.
Here's a snip from the service I made:
clickApp.factory('client', ['$http', function($http){
var logoUrl = "first";
var getConfig = function() {
logoUrl = "second";
$http({method: 'GET', url: base_url+'app-config.json'}).
success(function(data, status) {
// this callback will be called asynchronously
// when the response is available
// console.log("data",data);
console.log("logopre",logoUrl);
logoUrl = "third";
console.log("logopost",logoUrl);
}).
error(function(data, status) {
console.log("error",status);
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
getConfig();
return {
logoUrl: logoUrl
}
}]);
I have a controller hooked up to this which just fills a p tag with logoUrl for the moment. With this code, the p tag is immediately updated to "second", the log value of "logopre" is "second" and the log value of "logopost" is "third", but the controller does not update the p tag to "third" like I expect.
I tried some fancy $scope.$watch statement in my controller as well, but that doesn't change the result.
edit I should note that I also tried $rootScope.$apply after the $http request but I could only get "$digest already in progress" errors.
How can I properly update this value so it's reflected in my controller after the $http request?
Upvotes: 0
Views: 343
Reputation: 5729
Try something like this (http://plnkr.co/edit/Fnrgo4?p=preview):
app.controller('MainCtrl', function($scope, client) {
$scope.client = client;
$scope.$watch(function() {
return client;
}, function(client) {
$scope.logoUrl = client.logoUrl;
}, true);
});
app.factory('client', function($http, $log, $timeout) {
var obj = {
logoUrl: "first"
};
$log.info("logoinit", obj);
var getConfig = function() {
obj.logoUrl = "second";
$http({
method: 'GET',
url: 'app-config.json'
}).
success(function(data, status) {
$log.info("logopre", obj);
obj.logoUrl = "third";
$log.info("logopost", obj);
}).
error(function(data, status) {
$log.error("error", status);
});
};
getConfig();
return obj;
});
Upvotes: 1