简体   繁体   English

AngularJS在控制器之间共享复制的对象

[英]AngularJS share copied object across controllers

In my AngularJS project, I am not able to share data of copied objects across different controllers. 在我的AngularJS项目中,我无法跨不同的控制器共享复制对象的数据。

I am able to share data properly if I set the properties in code but if I copy the object then it does not appear to work. 如果我在代码中设置属性,则能够正确共享数据,但是如果我复制对象,则该对象似乎无法正常工作。

In the code block at the JSFiddle , you will see that I have two objects User and OriginalUser . JSFiddle的代码块中,您将看到我有两个对象UserOriginalUser As soon as the FirstCtrl is loaded, I copy the User object to the OriginalUser object. 加载FirstCtrl ,我立即将User对象复制到OriginalUser对象。

You will see that while the value assigned to User object in FirstCtrl is accessible in SecondCtrl but the data of OriginalUser is accessible only in the FirstCtrl . 你会看到,而分配给值User在对象FirstCtrl是在访问SecondCtrl但数据OriginalUser仅在访问FirstCtrl

You can see the code in action at Code Sample at JSFiddle 您可以在JSFiddle的“代码示例”中查看运行中的代码

This is because you are not update OriginalUser data but you create a new variable using angular.copy function. 这是因为您不是在更新OriginalUser数据,而是使用angular.copy函数创建了一个新变量。

What you are looking for is angular.extend which will copy user properties to your original user. 您正在寻找的是angular.extend,它将用户属性复制到原始用户。 Now, both controllers use the same object instance. 现在,两个控制器使用相同的对象实例。

Your first controller: 您的第一个控制器:

function FirstCtrl($scope,User, OriginalUser){
    $scope.user = User;
    $scope.o_user = angular.extend(OriginalUser, $scope.user);
}

Your fiddle is up to date. 您的小提琴是最新的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM