[英]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:任务:
I am getting confused of what is the best solution for this approach.我对这种方法的最佳解决方案感到困惑。
There are many different ways to achieve this..有很多不同的方法可以实现这一点..
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.