$ http JSON请求在angularjs

时间:2016-02-03 15:39:48

标签: javascript angularjs json http

我正在使用angularJS从文件中获取JSON数据。这样做它不会让我得到文件中的数据。我的plunker link

HTML

<body ng-controller="MainCtrl">
    <div ng-repeat="(key, data) in groupedByFoodName">
      <p>{{key}} {{data.length}}</p>
    </div>
</body>

控制器

app.controller('MainCtrl', function($scope,$http) {

 $http({
  method: 'GET',
  url: 'list.json'
  }).then(function successCallback(response) {
    $scope.lists = response.data;
  });
 $scope.groupedByFoodName=  _.groupBy($scope.lists, function (each) { return each.orderfood[0].name });

});

1 个答案:

答案 0 :(得分:5)

您必须将结果的分组移动到.then方法中,否则在获得get请求的结果之前将调用它:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,$http) {

$http({
        method: 'GET',
        url: 'https://safe-depths-4702.herokuapp.com/api/orders'
    }).then(function successCallback(response) {
        $scope.orders = response.data;
        $scope.groupedByFoodName=  _.groupBy($scope.orders, function (each) { 
          if(each.orderfood.length > 0) 
            return each.orderfood[0].name; 
        });
    });
});