javascript - Getting the object obtained from asynchronous $http service in angularJS to be accessible globally in $scope -
i working using angular js. trying json object obtained using $http service accessible in $scope variable. inside asynchronous ajax ($http.get()) calls, if try print data obtained stored inside $scope variable , print it, works , shows me expected data. outside scope of asynchronous method, same $scope variable assigned data obtained loses hold of , prints undefined.
code:
var app = angular.module('chariot', ['ngroute', 'ngfileupload']); app.factory('gettestcasefactory', ['$http', '$routeparams', '$q', function($http, $routeparams, $q) { return { list: function(){ var deferred = $q.defer(); $http.get('/testcase/' + $routeparams.testcase) .success(function(data, status, headers, config) { deferred.resolve(data); }) .error(function(data, status, headers, config) { deferred.reject("error fetching xml file: " + status + ' ' + json.stringify(headers)); }); return deferred.promise; } }; } ]); app.controller('testcasecapctrl', ['$scope', '$routeparams', '$http', 'gettestcasefactory', function($scope, $routeparams, $http, gettestcasefactory) { $scope.myjsonobj = ''; var fetchtestcasedetails = function() { gettestcasefactory.list() .then( function(data) { $scope.xml.file = data; var x2js = new x2js(); var jsonobj = x2js.xml_str2json($scope.xml.file); $scope.xml.json = json.stringify(jsonobj, null, 2); $scope.model = jsonobj; console.log($scope.model);//prints right data }, function(data) { alert(data); }); } fetchtestcasedetails(); console.log($scope.model); //prints undefined }]);
by time
console.log($scope.model);
executes, $http
request have not gone through yet, , why prints undefined. once $http
request done, $scope.model
update accordingly. can test using $timeout
$timeout(function () { console.log($scope.model); }, 5000);
don't forget inject $timeout
in controller.
Comments
Post a Comment