保存到范围变量时$ http获取响应数据问题

时间:2014-05-29 11:28:17

标签: javascript angularjs angularjs-scope

下面是将返回值分配给范围变量时遇到问题的代码。

app.factory("appService",function($http){
  var promise;
  var lists = {
    async: function() {
      var promise = $http.get("http://localhost:81/hrms/public/languagesService").then(function (response) {
        return response.data;
      });
      return promise;
    }
  };
  return lists;
});

$http获取的响应成功,状态码为200.以下是使用控制器中的上述服务的代码

app.controller("AppCtrl",function(appService,$scope,$http,$filter) {
  $scope.language = "";

  var sortingOrder = 'id';
  $scope.sortingOrder = sortingOrder;
  $scope.reverse = false;
  $scope.filteredItems = [];
  $scope.groupedItems = [];
  $scope.itemsPerPage = 4;
  $scope.pagedItems = [];
  $scope.currentPage = 0;
  $scope.items = [];


  $scope.itemlist = function() {

    appService.async().then(function(d){
      $scope.data = d;
    });

  }

  $scope.items = $scope.itemlist();

但是$scope.items是空的。请指导我如何将值传递给$scope.items。我也试过$scope.items.push(d),但似乎没有任何作用......

我想要的是$scope.items来保存$http.get()的回复数据。

2 个答案:

答案 0 :(得分:0)

我猜,响应是数组。因此,您可以返回空数组,然后在响应将被传递之后填充数据:

$scope.itemlist = function() {
   var result = [];
   appService.async().then(function(d){
      $scope.data = d;
      result.push.apply(result,d);
   });
   return result;
};

$scope.items = $scope.itemlist();

我们一次使用apply方法push多个元素。

答案 1 :(得分:0)

您好,为什么不将d分配给$ scope.items,如下所示

app.controller("AppCtrl",function(appService,$scope,$http,$filter) {
  $scope.language = "";

  var sortingOrder = 'id';
  $scope.sortingOrder = sortingOrder;
  $scope.reverse = false;
  $scope.filteredItems = [];
  $scope.groupedItems = [];
  $scope.itemsPerPage = 4;
  $scope.pagedItems = [];
  $scope.currentPage = 0;
  $scope.items = [];

  appService.async().then(function(d){
      $scope.items = d;
    });
})