How to alter the data returned by $resource in Angular.js?

Viewed 16592

I'm using an API that returns JSON data in this format:

{
    paging: {
        previous: null,
        next: null
},
    data: [
        { title: 'First Item' },
        { title: 'Second Item' },
        ...
    ]
}

I'm using Angular's $resource service to fetch this data.
My code - which is located in a controller - goes something like this:

var Entity = $resource('/api/entities');
var entities = $scope.entities = Entity.get();

And then, in the view, I can display the data like this:

<ul>
  <li ng-repeat="entity in entities.data">{{entity.title}}</<li>
</ul>

It all works fine, but:

  • I'd rather expose only the contents of entities.data to the view, instead of the whole entities object. How can I intercept the data returned by the GET request to modify it before it populates $scope.entities?
  • Correlated question: since I am fetching an array of data, it would be cleaner to use Entity.query() instead of Entity.get(). But if I use Entity.query() in the code above, I get an error "TypeError: Object # has no method 'push'". This makes sense, since the API is returning an object instead of an array (hence, no 'push' method on the object). Again, if I could extract the .data attribute from the response, I'd have an array.

Following these indications by Dan Boyon, I managed to customize the default $resource service and to override the .get() or .query() methods, but I'm not sure where to go from there.

2 Answers
Related