Answer the question
In order to leave comments, you need to log in
How to access data from $hhtp.get() in angularJS?
Hello. The essence of the problem:
<div class="ng-scope" ng-init="init_func()" ng-controller="testCtrl">
var testApp = angular.module('testApp', []);
testApp.controller("testCtrl", ['$http', function($http){
var store = this;
store.init_func = function(){
$http.get('/get_json_data')
.success(function(data){
store.my_data = data;
})
};
console.log(store);
console.log(store.my_data);
}]);
Object { init_func=function()}
undefined
var testApp = angular.module('testApp', []);
testApp.controller("testCtrl", ['$scope', '$http', function($scope, $http){
$scope.init_func = function(){
$http.get('/get_json_data')
.success(function(data){
$scope.my_data = data;
})
};
console.log($scope);
console.log($scope.my_data);
}]);
l { $$listeners={...}, $$listenerCount={...}, $id=2, ещё...}
undefined
Answer the question
In order to leave comments, you need to log in
You seem to have misunderstood how ajax requests work.
Synchronous requests are bad for performance, which is why Angular uses a mechanism similar to Promises.
Accordingly, the data will not come immediately and nothing correct will be displayed in the console.
The bottom line is that the request takes a certain time and the callback is called only when it is completed.
Roughly speaking, inside the callback, after the operations performed, you need to call scope.$apply() to apply the model changes and even then you can be sure that the data has arrived.
You need to call store.init_func.
Try like this:
var testApp = angular.module('testApp', []);
testApp.controller("testCtrl", ['$http', function($http){
var store = this;
store.init_func = function(){
$http.get('/get_json_data')
.success(function(data){
store.my_data = data;
})
};
store.init_func();
console.log(store);
console.log(store.my_data);
}]);
$scope.$watch 'my_data', (data) ->
console.log($scope)
console.log($scope.my_data)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question