Strip or overwrite an AngularJS $resource

安稳与你 提交于 2019-12-24 15:33:43

问题


I need to copy data from one resource to another. Problem is that the $get, $save etc methods on the old resource remain when wrapping an old resource in a new resource.

Example: http://plnkr.co/edit/d2oHwm?p=preview

var myApp = angular.module('myApp', ['ngResource'])

myApp.controller('MyCtrl', function($scope, $resource) {

    var ResourceA = $resource('A');

    var ResourceB = $resource('B');

    var instances = {};
    instances.A = new ResourceA({
        label: "Loading..."
    });

    instances.B = new ResourceB(instances.A); // <-- trouble

    instances.B.$get(function() {
        $scope.instances.B = arguments[0]
    });

    $scope.instances = instances;
});

I don't want to keep a separate object with the clean data of ResourceA because the object can be modified in multiple places. I also rather don't want to write a foreach loop to fetch the pure data.

Can I get a copy of the pure data in a ResourceA without the magic methods? Or is there some other way to ignore/strip/overwrite the magic methods in a resource?

Background info: A user can create/modify a template (resourceA). The user can use that template to create a new object (ResourceB). When that happens, the object needs to inherit all properties from the template, except for the $resource methods.


回答1:


Angular.toJson method will strip dollar-prefixed properties from the object. So, this method, in pair with angular.fromJson, will provide you with "clean" resource:

var myApp = angular.module('myApp', ['ngResource']);

myApp.controller('MyCtrl', function($scope, $resource) {

  var ResourceA = $resource('A');

  var ResourceB = $resource('B');

  var instances = {};
  instances.A = new ResourceA({
      label: "Loading A ..."
  });

  var copy = angular.fromJson(angular.toJson(instances.A));
  instances.B = new ResourceB(copy);

  instances.B.$get(function(response) {
      $scope.instances.B = response;
  });

  $scope.instances = instances;
});


来源:https://stackoverflow.com/questions/20683166/strip-or-overwrite-an-angularjs-resource

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