I want to create a $saveOrUpdate function which will accept a success callback and I want to use that function on an instance of my $resource service, and not extend the service itself.
So, if I want to extend the service, I simply write something along these lines:
angular
.module('company-registry.company')
.factory('Company', Company);
Company.$inject = ['$resource'];
function Company($resource) {
var companyService = $resource("https://api.mongolab.com/api...", { update: { method: 'PUT' } });
angular.extend(companyService, {
saveOrUpdate: function(company, successCallback) {...}
});
return companyService;
}
This creates the saveOrUpdate function on the actual service, but what I want is to have the following code work:
var company = new Company();
company.$saveOrUpdate(cb);
I have two questions here:
since my $saveOrUpdate method will have to call $save or $update on my company, how do I reference the object on which the function is being called?
How do I extend the methods available on the instances of my service?
Try this:
function Company($resource) {
var companyService = $resource("https://api.mongolab.com/api...", { update: { method: 'PUT' } });
return angular.extend({
"$saveOrUpdate":function(cb){
...
}
}, companyService);
}
Edit: Changes made based on comment. Take a look at this Fiddle. Does this make more sense? The order of the object in extend
method does matter. Depends on whether you want to add new properties to the existing object or create a new one by extending the other. You can self-reference the Company
using this
as shown in the example.
return angular.extend({
hello: function (text) {
console.log(text);
return text + " - OK";
},
saveOrUpdate: function (successCallback) {
var response = this.hello("Foo Bar!");
return successCallback(response);
}
}, companyService);