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: javascript
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。 html
jsfiddle連接:http://jsfiddle.net/whitewolf/5JBA7/ java