簡體   English   中英

Angular JS:$ http.get()數據未更新為View

[英]Angular JS : $http.get() data is not being updated to View

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

        };

我基本上是在視圖(index.html)中用ng-repeat遍歷對象數組,但是當我使用$ http服務時它沒有得到更新。但是靜態數據卻可以正確顯示。 我正在瀏覽一些在線AngularJs教程。 我是AngularJs的新手。 請指出我在這里做錯了什么? 謝謝

嘗試這個 :

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);
});
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);
  };
}]);

這是這樣做的方法,您首先創建一個方法並在其中添加http內容。 在成功響應中調用另一個方法並打印出來。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM