问题
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