javascript - $scope variable value not accessible outside of $http success callback in AngularJS -
javascript - $scope variable value not accessible outside of $http success callback in AngularJS -
i started learning angularjs.
i created simple app display content in json file. the info assigned scope within $http, returns undefined outside.
var app= angular.module('app',[]); app.controller('apctrl',['$scope','$http',function($scope,$http){ $http.get('/path/to/data.json').success(function(){ console.log(data); // returns info --working $scope.data=data; // assiged console.log($scope.data); // returns info --working }); console.log($scope.data); // returns 'undefined' --not working }]);
please help me understand problem.
thanks!
it's because making asynchronous call. info not prepared when seek phone call outside of success function. check documentation.
for example, if wait couple seconds, it'ld show:
app.controller('apctrl',['$scope','$http','$timeout',function($scope, $http, $timeout){ $http.get('/path/to/data.json').success(function(){ console.log(data); // returns info --working $scope.data=data; // assiged console.log($scope.data); // returns info --working }); $timeout(function(){ console.log($scope.data); }, 2000); }]);
javascript angularjs angularjs-scope
Comments
Post a Comment