angularjs - How do I change data after an $http request? -
i'm making web app in angular driven data remote json objects. want load page sensible default data, request json objects , update controllers new data.
here's snip service 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) { // callback called asynchronously // when response 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 error occurs // or server returns response error status. }); }; getconfig(); return { logourl: logourl } }]);
i have controller hooked fills p tag logourl moment. code, p tag updated "second", log value of "logopre" "second" , log value of "logopost" "third", controller not update p tag "third" expect.
i tried fancy $scope.$watch statement in controller well, doesn't change result.
edit should note tried $rootscope.$apply after $http request "$digest in progress" errors.
how can update value it's reflected in controller after $http request?
try (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; });
Comments
Post a Comment