在 angular $resource 上添加自定义函数
我有一个类似这样的 angular 资源
I have an angular resource that goes something like 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 i want to have full name in the view, can i add a method so that when i do this
$scope.user = User().current();
而不是在 html 中执行以下操作
instead of doing the following in html
<p>{{ user.first_name }} {{ user.last_name }}</p>
我这样做
<p>{{ user.get_full_name }}</p>
有没有办法将此属性添加到$resource
?
is there a way to add this property to the $resource
?
您可以使用 transformResponse 将其添加为属性,但我是否建议向每个返回组合的名字和姓氏的对象添加一个方法:
You can add it as a property using transformResponse, but might I suggest just adding a method to every object that returns the combined first and 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 any methods here using prototype
User.prototype.get_full_name = function() {
return this.first_name + ' ' + this.last_name;
};
return User;
});
然后使用:
<p>{{ user.get_full_name() }}</p>
使用原型添加的任何函数都将添加到您的服务返回的每个对象上.如果您需要对服务属性进行复杂的获取或设置,这是添加辅助方法的好方法.
Any functions added using prototype will be added onto every object returned by your Service. It is a great way to add helper methods if you need to do complicated getting or setting of service properties.