AngularJS: $resource custom methods not being called


I have a resource defined for which I have defined a custom method. In my template, I am not able to hit this method. My code looks like this. The getName() function is not being called. What am I missing here

personservices.factory("Person", ["$resource", function($resource) {
  var Persons =  $resource("", {}, {
  query: {method:'GET'}
});                                                       

 Persons.prototype.getName = function () {
   /* do something */ 
   return name;
  }
  return Persons;
}]); 


<ul>
  <li ng-repeat="person in persons">
    {{ person.getName() }} -> not being called
    {{ person.id }} 
  </li>
</ul>

$scope.Persons = Person.query() -> works perfectly

Your problem is:

  1. You want a list of persons, but your returned data is not a list. So you can use transformResponse in your service to transform object to array.

  2. Function getName should return this.name, not name.

    app.factory("Persons", ["$resource", function($resource) {
        var Persons =  $resource("", {}, {
            query: {
                method:'GET',
                isArray: true,
                transformResponse: function(data, header) {
                    return angular.fromJson(data).items;
                }
            }
        });                                                       
    
        Persons.prototype.getName = function () {
            /* do something */ 
            return this.name;
        }
    
        return Persons;
    }]);
    

Here is an JSFiddle example: http://jsfiddle.net/9JFhA/1/


Your example service was defined almost perfectly, the only change I made was that I added anisArray: true to your custom query function, because it return a list of persons.

var Persons =  $resource("/person", {}, {
query: {method:'GET', isArray: true}

});

Maybe that's why your custom method was not being called.

Have a look at the working plunker I made: http://plnkr.co/edit/2i7IHs?p=preview, which tests a custom method's function in a $resource service.