Angular JS:$ http.get()数据未更新为View

时间:2017-02-28 13:38:33

标签: javascript angularjs

的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

        };

我基本上在我的视图中使用ng-repeat迭代对象数组(index.html)但是当我使用$ http服务时它没有获得更新。但是静态数据正在正确显示。 我将通过一些在线AngularJs教程。我是AngularJs的新手。请指出我在这里做错了什么?感谢

2 个答案:

答案 0 :(得分:2)

试试这个:

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

答案 1 :(得分:1)

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内容。在成功响应中调用另一个方法并将其打印出来。