angularjs - add a custom function on angular $resource -
this question has answer here:
i have angular resource goes this
app.factory('user', function ($resource) { return $resource( '/api/user/:listctrl:id/:docctrl/', { id: '@id', listctrl: '@listctrl', docctrl: '@docctrl' }, { update: { method: 'put' }, current: { method: 'get', params: { listctrl: 'current' } }, nearby: { method: 'get', params: { docctrl: 'nearby' }, isarray: true } } ); });
now want have full name in view, can add method when this
$scope.user = user().current();
instead of doing following in html
<p>{{ user.first_name }} {{ user.last_name }}</p>
i this
<p>{{ user.get_full_name }}</p>
is there way add property $resource
?
you can add property using transformresponse, might suggest adding method every object returns combined first , last name:
app.factory('user', function ($resource) { var user = $resource( '/api/user/:listctrl:id/:docctrl/', { id: '@id', listctrl: '@listctrl', docctrl: '@docctrl' }, { update: { method: 'put' }, current: { method: 'get', params: { listctrl: 'current' } }, nearby: { method: 'get', params: { docctrl: 'nearby' }, isarray: true } } ); // add methods here using prototype user.prototype.get_full_name = function() { return this.first_name + ' ' + this.last_name; }; return user; });
then use:
<p>{{ user.get_full_name() }}</p>
any functions added using prototype added onto every object returned service. great way add helper methods if need complicated getting or setting of service properties.
Comments
Post a Comment