AngularFrance AngularFrance - 8 months ago 29
AngularJS Question

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

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:

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

It all works fine, but:

  • I'd rather expose only the contents of
    to the view, instead of the whole
    object. How can I intercept the data returned by the GET request to modify it before it populates

  • Correlated question: since I am fetching an array of data, it would be cleaner to use
    instead of
    . But if I use
    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
    attribute from the response, I'd have an array.

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


I don't think you need to modify the get or query defaults. Just use the success callback to do what you want. It should be more robust as well.

    {}, //params
    function (data) {   //success
        $scope.entities =;
    function (data) {   //failure
        //error handling goes here

Html will be cleaner, too:

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

By the way, I usually declare services for my resources and then inject them into my controllers as I need them.

 myServices.factory('Entity', ['$resource', function ($resource) {
     return $resource('/api/entities', {}, {