javascript 在 angular $resource 上添加自定义函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18138147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
add a custom function on angular $resource
提问by Yousuf Jawwad
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();
instead of doing the following in html
而不是在 html 中执行以下操作
<p>{{ user.first_name }} {{ user.last_name }}</p>
i do this
我这样做
<p>{{ user.get_full_name }}</p>
is there a way to add this property to the $resource
?
有没有办法将此属性添加到$resource
?
回答by Jeremy Zerr
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:
您可以使用transformResponse将其添加为属性,但我是否建议只向每个返回组合的名字和姓氏的对象添加一个方法:
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;
});
Then use:
然后使用:
<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.
使用原型添加的任何函数都将添加到您的服务返回的每个对象上。如果您需要对服务属性进行复杂的获取或设置,这是添加辅助方法的好方法。
回答by Yousuf Jawwad
after playing for a while with angular, I think a customer filter would be a much wiser approach, rather than adding a property on $resource.
在使用 angular 玩了一段时间后,我认为客户过滤器将是一种更明智的方法,而不是在 $resource 上添加属性。
here is how to do a filter
这里是如何做一个过滤器
app.filter('getFullName', function () {
return function (input) {
if (input) {
return input.first_name + ' ' + input.last_name;
} else {
return 'default';
}
};
});
回答by falinsky
I think you should look at transformResponse
way.
我想你应该看看transformResponse
方式。
Btw, what version of angularjs
do you use?
Btw,angularjs
你用的是什么版本?