Angular 组件间的通讯

 Angularjs在scope中为我们提供了冒泡和隧道机制,

$broadcast会把事件广播给所有子controller,

而$emit则会将事件冒泡传递给父controller

 

view:
<div ng-app="app" ng-controller="parentCtr">
<div ng-controller="childCtr1">name :
<input ng-model="name" type="text" ng-change="change(name);" />
</div>
<div ng-controller="childCtr2">Ctr1 name:
<input ng-model="ctr1Name" />
</div>
</div>

 

controller:

angular.module("app", []).controller("parentCtr",
function($scope) {
$scope.$on("Ctr1NameChange",

function(event, msg) {
console.log("parent", msg);
$scope.$broadcast("Ctr1NameChangeFromParrent", msg);
});
}).controller("childCtr1", function($scope) {
$scope.change = function(name) {
console.log("childCtr1", name);
$scope.$emit("Ctr1NameChange", name);
};
}).controller("childCtr2", function($scope) {
$scope.$on("Ctr1NameChangeFromParrent",

function(event, msg) {
console.log("childCtr2", msg);
$scope.ctr1Name = msg;
});
});

posted on 2016-04-27 18:43  流光易逝  阅读(168)  评论(0编辑  收藏  举报

导航