本文共 1479 字,大约阅读时间需要 4 分钟。
在随笔中提到我们需要按照业务却分angular controller,避免过大无所不能的上帝controller,我们把controller分离开了,但是有时候我们需要在controller中通信,一般为比较简单的通信机制,告诉同伴controller我的某个你所关心的东西改变了,怎么办?如果你是一个javascript程序员你会很自然的想到异步回调响应式通信—事件机制(或消息机制)。对,这就是angularjs解决controller之间通信的机制,所推荐的唯一方式,简而言之这就是angular way。
12name :3 45Ctr1 name:6 78
Controller:
1 angular.module("app", []).controller("parentCtr", 2 function ($scope) { 3 $scope.$on("Ctr1NameChange", 4 5 function (event, msg) { 6 console.log("parent", msg); 7 $scope.$broadcast("Ctr1NameChangeFromParrent", msg); 8 }); 9 }).controller("childCtr1", function ($scope) {10 $scope.change = function (name) {11 console.log("childCtr1", name);12 $scope.$emit("Ctr1NameChange", name);13 };14 }).controller("childCtr2", function ($scope) {15 $scope.$on("Ctr1NameChangeFromParrent",16 17 function (event, msg) {18 console.log("childCtr2", msg);19 $scope.ctr1Name = msg;20 });21 });
这里childCtr1的name改变会以冒泡传递给父controller,而父controller会对事件包装在广播给所有子controller,而childCtr2则注册了change事件,并改变自己。注意父controller在广播时候一定要改变事件name。
jsfiddle链接:
本文转自破狼博客园博客,原文链接:http://www.cnblogs.com/whitewolf/archive/2013/04/16/3024843.html,如需转载请自行联系原作者