Is it possible to add virtual attributes to a ngResource? I created a service like this
app.factory('Person', ['$resource', function($resource) {
return $resource('api/path/:personId', {
personId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}])
Person
has an attribute name
and an attribute surname
.
I want to retrive the fullname
by adding a virtual attribute fullname
returning resource.name + resource surname
.
I know I could add it in the controller, but adding it to the service it will make it much more portable.
I tried something like this
app.factory('Person', ['$resource', function($resource) {
return $resource('api/path/:personId', {
personId: '@_id'
}, {
update: {
method: 'PUT'
},
fullname: function(resource){
return resource.name + ' ' + resource.surname;
}
});
});
}])
but it doesn't work.
You could try intercepting the response from the Person resource and augment the response. Like this:
app.factory('Person', ['$resource', function($resource) {
function getFullName(){
return this.name + ' ' + this.surname;
};
return $resource('api/path/:personId', {
personId: '@_id'
}, {
update: {
method: 'PUT'
},
'get': {method:'GET', isArray:false,interceptor:{
'response': function(response) {
response.fullname = getFullName; //augment the response with our function
return response;
}
}}
});
}]);
As per the docs, $resource
returns a constructor. You can leverage the usual prototype
of the constructor to add members, i.e.:
var Person = $resource('api/path/:personId', {
personId: '@_id'
}, {
update: { method: 'PUT' }
}); // same as the 1st snippet from the question
Person.prototype.xxxx = ...;
return Person; // from your Angular service
In the previous example xxxx
can be anything normally allowed in a prototype. If what you want is actually a derived property, i.e. a JS property that will always reflect the name
and surname
properties, then you need a fairly recent browser that supports Object.defineProperty()
and replace the Person.prototype
line above with:
Object.defineProperty(
Person.prototype,
"fullname",
{get: function() { return this.name + " " + this.surname; }}
);
If you only need the derived property for display purposes, you can create a display filter rather than loading up your model with redundant data:
app.filter('personFullName', function() {
return function(person) {
return person.name + " " + person.surname;
};
})
Then reference the filter in your template:
<div>
<p>{{person | personFullName}}</p>
<p>- should match -</p>
<p>{{person.name}} {{person.surname}}</p>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With