Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 347
suprita shankar Avatar asked Oct 21 '22 23:10

suprita shankar


1 Answers

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/

like image 112
frkk Avatar answered Oct 29 '22 19:10

frkk