前端之家收集整理的这篇文章主要介绍了
AngularJS controller之间的通信方式,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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',data) {
console.log(data); //子级得不到值
});
});
phonecatControllers.controller('ChildCtrl',function($scope){
$scope.$on('to-child',data) {
console.log(data); //子级能得到值
});
$scope.$on('to-parent',data) {
console.log(data); //父级得不到值
});
});
phonecatControllers.controller('BroCtrl',function($scope){
$scope.$on('to-parent',data) {
console.log(data); //平级得不到值
});
$scope.$on('to-child',data) {
console.log(data); //平级得不到值
});
});
原文链接:https://www.f2er.com/angularjs/146907.html