Question

I have a simple app that returns objects from a REST API and binds them to a scope var. This works OK, but if I try to do any work on the objects returned from the $resource promise, the objects are undefined.

I put together this plunkr to reproduce the behaviour using the $q service. The first part binds a simple array to the scope, the second gets the same array via a deferred object. The third gets the array via a deferred object again then tries to apply some simple logic to the returned object. Unfortunately the returned object has no 'length' attribute. Clearly I am missing something, presumably some usage of $scope.$apply but I've had no luck there either.

What am i doing wrong?

Was it helpful?

Solution

You need to use then with your promise.

asyncInit().then(function(data){
  $scope.deferredPersons = data;
});

From here on, you have access to your data per usual, and can call .length on it. Note, you should always handle errors when using promises, otherwise it can get hard to debug.

OTHER TIPS

If you want to use length, use deferredPersons.then.length

if (deferredPersons.then.length > 0)

plunkr

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top