Reputation: 294
Script.js
var app=angular.module("myapp",["panelModule"]);
var store=this;
store.products=[];
//following code yield proper output
// app.controller("StoreController",function () {
// this.products=data; //data is a array of object defined in same file
// });
app.controller("StoreController",['$http',function($http){
return $http.get('js/data.json').then(onDataReceive);
}]);
var onDataReceive=function(response) {
store.products.push(...response.data);
console.log(store.products); //this shows [object, object] in browser console
};
I m basically iterating over the array of object with ng-repeat in my view( index.html) But it is not getting update when i used $http service.However static data is getting displayed properly. I m going thru some online AngularJs tutorial. I m new to AngularJs. Please point me out what i m doing wrong here? Thanks
Upvotes: 0
Views: 78
Reputation: 27192
Try this :
var app = angular.module("myapp", ["panelModule"]);
app.controller("StoreController", ['$http', function($http) {
var store = this;
store.products = [];
getData = function() {
return $http.get('js/data.json').then(function(response) {
$scope.data = response.data;
});
}
// do the ajax call
getData().then(function(data) {
// stuff is now in our scope, I can alert it
store.products = $scope.data;
console.log(store.products);
});
Upvotes: 2
Reputation: 3113
var app = angular.module("myapp", ["panelModule"]);
app.controller("StoreController", ['$http', function($http) {
var store = this;
store.products = [];
gettingAPIData();
function gettingAPIData() {
$http.get('js/data.json').then(function(response) {
store.products. = response.data;
onDataReceive();
});
}
function onDataReceive() {
console.log(store.products);
};
}]);
This is the way to do it, you first create a method and do the http stuff in it. Call another method in the success response and print it out.
Upvotes: 1