add a custom function on angular $resource [duplicate]

微笑、不失礼 提交于 2019-11-27 01:49:22

问题


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

<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?


回答1:


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;
});

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.




回答2:


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.

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';
      }
    };
  });



回答3:


I think you should look at transformResponse way.

Btw, what version of angularjs do you use?



来源:https://stackoverflow.com/questions/18138147/add-a-custom-function-on-angular-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!