简体   繁体   English

如何在 AngularJS 中将数据从子控制器发送到父控制器?

[英]How to send data from child controller to Parent controller in AngularJS?

I need some guidance to take the best practice for my task in AngularJS.我需要一些指导来为我在 AngularJS 中的任务采取最佳实践。

Task:任务:

  1. Inside the view : I have one parent controller and two child controllers.视图内部:我有一个父控制器和两个子控制器。
  2. Child controllers work with their own $scope and objects.子控制器使用它们自己的 $scope 和对象。
  3. When I press save in the view, I need to get the data from child controllers to parent controller in order to prepare an object for posting it to the server.当我在视图中按保存时,我需要将数据从子控制器获取到父控制器,以便准备一个对象以将其发布到服务器。

I am getting confused of what is the best solution for this approach.我对这种方法的最佳解决方案感到困惑。

A common way of sharing data between controllers is to use use a service .在控制器之间共享数据的一种常见方式是使用服务

You could also broadcast updates to the parent controller您还可以向父控制器广播更新

There are many different ways to achieve this..有很多不同的方法可以实现这一点..

  1. Using $rootScope.使用 $rootScope。
  2. Using Services使用服务
  3. Use broadcast and emit使用广播和发射
  4. Declare an object in parent controller and then modify the same object in the child controller.在父控制器中声明一个对象,然后在子控制器中修改相同的对象。

Using $rootScope is not a good approach, as the $rootScope variable is destroyed when application is closed.使用 $rootScope 不是一个好方法,因为 $rootScope 变量在应用程序关闭时被销毁。

I will also not recommend broadCast or emit, until it's required.在需要之前,我也不会推荐广播或发射。

Services, is good for communication b/w controllers, but again you have inject it and modify the methods.服务,对于通信黑白控制器很有用,但是您再次注入它并修改方法。

In your, scenario, i would recommend to use the common $scope object variable, which is declared inside parent and used in child controllers, as all methods are inherited in the child controllers.在您的场景中,我建议使用公共 $scope 对象变量,该变量在父级内部声明并在子控制器中使用,因为所有方法都在子控制器中继承。

There are three common ways to share data between controllers:控制器之间共享数据的常用方法有以下三种:

1 put data in service or factory. 1 将数据放入服务或工厂。 Since they are singleton, any controller injected with same service can share the data within that service由于它们是单例的,任何注入相同服务的控制器都可以在该服务中共享数据

2 put data in $rootScope 2 将数据放入$rootScope

3 use $broadcast or $emit to send events between scopes, and pass the shared data as event arguments 3 使用$broadcast$emit在作用域之间发送事件,并将共享数据作为事件参数传递

Above answers are useful, but below is an simple way to update a $scope object in parent controller from child scope as below.上面的答案很有用,但下面是一种从子作用域更新父控制器中的$scope对象的简单方法,如下所示。

In child controller, $scope.$parent.parentObject = updatedObject在子控制器中, $scope.$parent.parentObject = updatedObject

Hope it helps!希望能帮助到你!

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

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