5

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

2
  • Where is people declared people.name? Commented Oct 14, 2013 at 14:13
  • I have edited the question. we can assume some computation that happens in getName and returns a string which is the name to be displayed in the template. Commented Oct 14, 2013 at 14:28

2 Answers 2

3

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/

1
  • this looks good but I get the error TypeError: Object #<g> has no method 'push'. what do you think might be the error Commented Oct 15, 2013 at 14:40
0

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.

1
  • But my data returned is not an array. Initially I had that. I was getting the error "object has no method push". Removed it and it worked perfect. Commented Oct 14, 2013 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.