Prototyping Angular Resources

ngResource is a useful Angular.js module which aids communication with RESTful data sources. ngResource objects can be extended using prototypes just like any other JavaScript object.

Let’s start with a simple resource called persons. Imagine that a person contains only a name and an id. An example record would be

{"id": 1, "name": "James"}

Now, let’s connect to the resource (which is hosted at using ngResource.

var PersonsResource = $resource('');

We don’t want our people to be rude, so let’s extend our resource to let them introduce themselves to the JavaScript console.

PersonsResource.prototype.introduce = function () {
  var introduction = "Hi, my name is " +;

Any people created using the resource will now be able to introduce themselves.

var james = PersonsResource.get({id: 1});
james.introduce(); // logs "Hi, my name is James"

var people = PersonsResource.query();
people[0].introduce(); // logs "Hi, my name is James"