在 angular $resource 上添加自定义函数 [英] add a custom function on angular $resource

查看:28
本文介绍了在 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.

这篇关于在 angular $resource 上添加自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆