在角控制器之间的通信 [英] Communication between controllers in Angular
问题描述
我熟悉下面的方法来实现控制器之间的通信。
I'm familiar with the following methods to implement communication between controllers.
有其他吗?有没有更好的方法/最佳做法?
Are there others? Are there better approaches / best practices?
.controller("Parent", function($scope){
$scope.$broadcast("SomethingHappened", {..});
$scope.$on("SomethingElseHappened", function(e, d){..});
})
.controller("Child", functions($scope){
$scope.$broadcast("SomethingElseHappened", {..});
$scope.$on("SomethingHappened", function(e, d){..});
})
.controller("AnotherChild", functions($scope){
$scope.$on("SomethingHappened", function(e, d){..});
});
或从视图:
<button ng-click="$broadcast('SomethingHappened', data)">Do Something</button>
优点:
- 适合一次性事件
缺点:
- 不兄弟姐妹之间的工作,除非一个共同的祖先,如
$ rootScope
,使用
- Does not work between siblings, unless a common ancestor, like
$rootScope
, is used
<div ng-controller="Parent">
<div ng-controller="Child">
<div ng-controller="ChildOfChild">
<button ng-click="someParentFunctionInScope()">Do</button>
</div>
</div>
</div>
,或在code
or, in code
.controller("ChildOfChild", function($scope){
$scope.someParentFunctionInScope();
});
优点:
- 适合高端到低端数据传播
缺点:
- 不-作为好为底部到顶部,因为它需要的对象(相对于原始的)
- 调用祖先的函数创建一个紧密耦合
- 不兄弟姐妹之间的工作,除非一个共同的祖先,如
$ rootScope
,使用
- Not-as-good for bottom-to-top, since it requires an object (as opposed to a primitive)
- Calling ancestor functions creates a tight coupling
- Does not work between siblings, unless a common ancestor, like
$rootScope
, is used
控制器才反应过来范围暴露的数据改变,永远不会调用函数。
Controllers only react to change in scope-exposed data and never call functions.
.controller("Parent", function($scope){
$scope.VM = {a: "a", b: "b"};
$scope.$watch("VM.a", function(newVal, oldVal){
// react
});
}
优点:
- 适合儿童的范围不是由控制器,例如创建像在
NG-重复
- Good for child scope not created by controllers, e.g. like within
ng-repeat
缺点:
- 不工作在所有的一次性事件
- 不是很可读code
- 共享服务与专业化的功能
- 更一般的Pub / Sub服务
-
$ rootScope
- Shared Service with specialized functionality
- More general Pub/Sub Service
$rootScope
推荐答案
我用的特定功能,共享服务控制器之间的通信。
I use functionality-specific shared services to communicate between controllers.
您可以创建一个通用的共享服务有一个中心点来订阅和广播事件,但我发现特定功能的服务更容易维护随着时间的推移,尤其是在项目和团队成长。
You can create a generic shared service to have a central point to subscribe to and broadcast events, but I find functionality-specific services to be easier to maintain over time, especially as the project and team grows.
这篇关于在角控制器之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!