Reputation: 411
I am just started learning AngularJS.
I created a simple app to display content in json file. But however the the data assigned to scope inside the $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 data --working
$scope.data=data; // assiged
console.log($scope.data); // returns data --working
});
console.log($scope.data); // returns 'undefined' --not working
}]);
Please help me to understand this problem.
Thanks!
Upvotes: 0
Views: 2651
Reputation: 13079
It's because you are making an asynchronous call. The data is not prepared when you try to call it from outside of success function. Check the documentation.
For example, if you wait for a 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 data --working
$scope.data=data; // assiged
console.log($scope.data); // returns data --working
});
$timeout(function(){
console.log($scope.data);
}, 2000);
}]);
Upvotes: 6