I have a model, defined using $resource
, that I am successfully loading.
Each loaded instance is, as promised, an instance of the class I defined.
I was looking for a solution to the same problem as yours. I came up with the following approach.
This example is based on Offers instead of Users, as domain entity. Also, please note here's a trimmed down version of the whole thing, which in my case spans over some files:
Domain entity custom class:
function Offer(resource) {
// Class constructor function
// ...
}
angular.extend(Offer.prototype, {
// ...
_init: function (resource) {
this._initAsEmpty();
if (typeof resource == 'undefined') {
// no resource passed, leave empty
}
else {
// resource passed, copy offer from that
this.copyFromResource(resource);
}
},
copyFromResource: function (resource) {
angular.extend(this, resource);
// possibly some more logic to copy deep references
},
// ...
});
Classic angular custom resource:
var offerResource = $resource(/* .. */);
Custom repository, passed to controller by a service factory:
function OfferRepository() {
// ...
}
angular.extend(OfferRepository.prototype, {
// ...
getById: function (offerId, success, error) {
var asyncResource = offerResource.get({
offerId: offerId
}, function (resource) {
asyncOffer.copyFromResource(resource);
(success || angular.noop)(asyncOffer);
}, function (response) {
(error || angular.noop)(response);
});
var asyncOffer = new offerModels.Offer(asyncResource);
return asyncOffer;
},
// ...
});
Most noticeable parts are: