Angularjs为在scope中为我们提供了冒泡和隧道机制,$broadcast会把事件广播给所有子controller,而$emit则会将事件冒泡传递给父controller,$on则是angularjs的事件注册函数,有了这一些我们就能很快的以angularjs的方式去解决angularjs controller之间的通信
实例
html code
<div ng-controller="ParentCtrl"> //父级
<div ng-controller="SelfCtrl"> //自己
<a ng-click="click()">click me</a>
<div ng-controller="ChildCtrl"></div> //子级
</div>
<div ng-controller="BroCtrl"></div> //平级
</div>
JavaScript code
phonecatControllers.controller('SelfCtrl', function($scope) {
$scope.click = function () {
$scope.$broadcast('to-child', 'child');
$scope.$emit('to-parent', 'parent');
}
});
phonecatControllers.controller('ParentCtrl', function($scope) {
$scope.$on('to-parent', function(d,data) {
console.log(data); //父级能得到值
});
$scope.$on('to-child', function(d,data) {
console.log(data); //子级得不到值
});
});
phonecatControllers.controller('ChildCtrl', function($scope){
$scope.$on('to-child', function(d,data) {
console.log(data); //子级能得到值
});
$scope.$on('to-parent', function(d,data) {
console.log(data); //父级得不到值
});
});
phonecatControllers.controller('BroCtrl', function($scope){
$scope.$on('to-parent', function(d,data) {
console.log(data); //平级得不到值
});
$scope.$on('to-child', function(d,data) {
console.log(data); //平级得不到值
});
});