0

I am using angularJS to get JSON data from a file. doing so it does not get me the data in the file. My plunker link

HTML

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

Controller

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 Answer 1

4

You have to move the grouping of your result into the .then method, otherwise it will be called before you have the result of the get request:

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; 
        });
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Your answer is what i am looking for but instead of list.json, feeding an API url does nor reflect any answers, API url plunk
@RohitKumarVinay This is because the external url does not always contain items with orderfood items in the array. When it does not contain items in the orderfood array, it will throw an error on each.orderfood[0].name because each.orderfood[0] is undefined. When you get errors in the grouping function, you will not receive any output. This kind of errors are visible in your browser console, use that to your advantage. I added an if statement to prevent those errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.