1

I'm using angular resource,

I'd like to extend any object returned by the factory with some computed properties from the object itself.

How can I add a post get step to the ngResource factory?

2 Answers 2

3

You could extend the prototype like this:

angular.factory('Person', ['$resource', function($resource) {
  var Person = $resource(...);

  ...

  Person.prototype.computedProp = this.prop1 + this.prop2;

  return Person;

}]);
Sign up to request clarification or add additional context in comments.

Comments

0

I haven't tested compatibility yet, but anyway I wanted to share how I did this to mantain Angular's style in my views code.

The idea is that the REST call gives me a distance in KM and a duration (in a format parseable by moment.js). What I wanted to achieve is computed property that would yield the average speed in KM/hour.

.factory('Times', function ($resource) {
  var Times = $resource("api/users/:userid/times/:id", {});
  Times.prototype.__defineGetter__("average_speed", function () {
    return this.distance / moment.duration(this.duration).asHours();
  });
  return Times;
})

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.