标签:blog http io ar java sp div on cti
在Angularjs开发一些经验总结随笔中提到我们需要按照业务却分angular controller,避免过大无所不能的上帝controller,我们把controller分离开了,但是有时候我们需要在controller中通信,一般为比较简单的通信机制,告诉同伴controller我的某个你所关心的东西改变了,怎么办?如果你是一个javascript程序员你会很自然的想到异步回调响应式通信—事件机制(或消息机制)。对,这就是angularjs解决controller之间通信的机制,所推荐的唯一方式,简而言之这就是angular way。
1 <div ng-app="app" ng-controller="parentCtr"> 2 <div ng-controller="childCtr1">name : 3 <input ng-model="name" type="text" ng-change="change(name);" /> 4 </div> 5 <div ng-controller="childCtr2">Ctr1 name: 6 <input ng-model="ctr1Name" /> 7 </div> 8 </div>
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。
标签:blog http io ar java sp div on cti
原文地址:http://www.cnblogs.com/Denny_Yang/p/4043808.html