Search code examples
angularjsangular-resourcemeanjs

How to loop through $resource returned query and get desired value?


I am using MEANJS

In my controller i have

// Find a list of Cars $scope.findHome = function() { $scope.cars = Cars.query(); console.log($scope.cars); };

Which outputs

enter image description here

here i want to get the _id string inside the first array 0: Resource

enter image description here

I tried $scope.cars[0]._id which returns undefined, Please help.


Solution

  • You are inspecting the results of the query immediately after the call, but ngResource is asynchronous, so perhaps the data has not yet returned from the server by the time you are trying to access it. Try putting your access in the callback function passed to query().

      $scope.cars = Cars.query(function() {
          console.log($scope.cars);
          console.log($scope.cars[0]._id);
      });