Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

javascript - Angular - extending $resource subobject with custom methods

In most cases the result of <custom-resource>.query() method is an array, which can be easily extended with some methods (business logics) with the following (factory) code:

var Data = $resource('http://..');
Data.prototype.foo = function() {return ...};

this is perfect for using with ng-repeat / ng-class, like so:

<tr ng-repeat="item in responseData" ng-class="{warning: item.foo()}">..</tr>

My problem is that every list response is encapsulated in an object which, besides the actual list, has some meta-properties (sorting info etc), so the final object returned is like this:

{ order_field: "name", items: [{..}, {..},{..}] }

Now, how do I make the same thing as previously with ng-repeat/ng-class?

<tr ng-repeat="item in responseData.items" ng-class="????">..</tr>

the previous method won't work as the "foo" method is defined on responseData and NOT on item object

Is there any way to directly extend the base class used for instantiating objects on the list?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've found that problem before, and the solution seems to be transformResponse, as John Ledbetter says in the other answer.

Anyway, if you need to keep the entire object, and also having the array in 'items' filled with instances of the resource, you might be able to do it with the following trick:

Taking the example from John's answer, and modifying it a bit:

angular.module('foo')

  .factory('Post', ['$resource', function($resource) {

    var Post = $resource('/api/posts/:id', { id: '@id' }, {
      query: {
        method: 'GET',
        isArray: false, // <- not returning an array
        transformResponse: function(data, header) {
          var wrapped = angular.fromJson(data);
          angular.forEach(wrapped.items, function(item, idx) {
             wrapped.items[idx] = new Post(item); //<-- replace each item with an instance of the resource object
          });
          return wrapped;
        }
      }
    });

    Post.prototype.foo = function() { /* ... */ };

    return Post;
  }]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...