地带或覆盖AngularJS $资源 [英] Strip or overwrite an AngularJS $resource

查看:210
本文介绍了地带或覆盖AngularJS $资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将数据从一个资源复制到另一个。问题是,旧的资源 $ GET $保存等方法,在新包装旧的资源时仍资源

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.

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

我不希望保留独立的对象, ResourceA 的干净的数据,因为该对象可以在多个地方进行修改。我也比较不想写一个foreach循环来获取纯数据。

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.

我可以得到纯净的数据在 ResourceA 副本没有魔术方法?还是有一些其他的办法忽略/条/覆盖资源的魔术方法?

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?

背景信息:用户可以创建/修改的模板( resourceA )。用户可以使用该模板来创建新的对象( ResourceB )。当这种情况发生时,对象需要从模板继承所有属性,除了 $资源方法。

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.

推荐答案

Angular.toJson方法将剥去对象以美元prefixed属性。所以,这个方法,对与 angular.fromJson ,将为您提供干净的资源:

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

这篇关于地带或覆盖AngularJS $资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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