javascript 如何在 AngularJS 中将数据从子控制器发送到父控制器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33202498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send data from child controller to Parent controller in AngularJS?
提问by Sajjad Ali Khan
I need some guidance to take the best practice for my task in AngularJS.
我需要一些指导来为我在 AngularJS 中的任务采取最佳实践。
Task:
任务:
- Inside the view : I have one parent controller and two child controllers.
- Child controllers work with their own $scope and objects.
- 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.
- 视图内部:我有一个父控制器和两个子控制器。
- 子控制器使用它们自己的 $scope 和对象。
- 当我在视图中按保存时,我需要将数据从子控制器获取到父控制器,以便准备一个对象以将其发布到服务器。
I am getting confused of what is the best solution for this approach.
我对这种方法的最佳解决方案感到困惑。
采纳答案by user2954587
回答by Ritesh
There are many different ways to achieve this..
有很多不同的方法可以实现这一目标。
- Using $rootScope.
- Using Services
- Use broadcast and emit
- Declare an object in parent controller and then modify the same object in the child controller.
- 使用 $rootScope。
- 使用服务
- 使用广播和发射
- 在父控制器中声明一个对象,然后在子控制器中修改相同的对象。
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.
服务,对于通信 b/w 控制器很有用,但您再次注入它并修改方法。
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 对象变量,该变量在父级内部声明并在子控制器中使用,因为所有方法都在子控制器中继承。
回答by Ram
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!
希望能帮助到你!
回答by MarkoCen
There are three common ways to share data between controllers:
在控制器之间共享数据有三种常见的方式:
1 put data in service or factory. Since they are singleton, any controller injected with same service can share the data within that service
1 将数据放入服务或工厂。由于它们是单例的,任何注入相同服务的控制器都可以在该服务中共享数据
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
在作用域之间发送事件,并将共享数据作为事件参数传递