Tadas Sasnauskas Tech/Engineering Blog

ngResource class and instance methods

One not really obvious ngResource trick is adding custom instance methods.

Say we have a user resource:

module.factory('User', function ($resource) {
  return $resource('/me');
}

ngResource generates some static (get for example) and instance ($get, $save, $delete) methods for us which is great. But what if we need something more?

First of all, start with declaring resource in wee bit different way:

module.factory('User', function ($resource) {
  var User = $resource('/me');
  return User;
}

Solution for adding a static method is obvious now, isn’t it?

module.factory('User', function ($resource, $cookies) {
  var User = $resource('/me');

  User.token = function() {
    return $cookies.get('token');
  };

  return User;
}

Instance method on the other hand is not:

module.factory('User', function ($resource, $cookies) {
  var User = $resource('/me');

  User.token = function() {
    return $cookies.get('token');
  };

  User.prototype.rememberMe = function() {
    $cookies.set('token', this.token);
  }

  return User;
}

In short - $resource method returns constructor function which is used to initialize the resource instances.

And one last thing: ngResource source code is a good read. Definitely check it out. It is surprisingly flexible for such small component.