一、父controller与子controller定义了相同的变量
父controller 与 子controller 有相同的变量 , 则优先使用子controller的变量 。若子controller没有,则往上查找。类似于js的作用链
二、通过声明$rootScope全局变量
app.run 可声明全局变量 $rootScope
语法:
var app = angular.module("apps", []).run(["$rootScope", function($rootScope) {
$rootScope.text = [];
(注意,在controller里用的时候需要传入 $rootScope 服务,此服务由ng模块生成。)
}]);
三、通过 broadcast /emit/on 等广播事件
html:
<body ng-controller="ParentCtrl">
<div>
<!--父级-->
<div ng-controller="SelfCtrl">
<!--自己-->
<a ng-click="click()">click me</a>
<div ng-controller="ChildCtrl"></div>
<!--子级-->
</div>
<div ng-controller="BroCtrl"></div>
<!--平级-->
</div>
</body>
js
app.controller('SelfCtrl', function($scope, $rootScope) {
$scope.click = function() {
$scope.$broadcast('to-child', 'child');
//往下传
$scope.$emit('to-parent', 'parent');
//往上传
$rootScope.$broadcast('to-all', 'allmagnize');
//根scope向下传(broadcast),可传给所有scope
//根scope向上传(emit),仅仅传给自己(rootScope)
}
}).controller('ParentCtrl', function($scope) {
$scope.$on("to-parent", function(event, args) {
event.stopPropagation(); //阻止继续往上传
console.log('parent', args);
});
$scope.$on("to-child", function(event, args) {
console.log('parent', args);
});
var aaa = $scope.$on("to-all", function(event, args) {
console.log('parent', args);
});
$scope.$on('aaa', function() {
deregister(); // 退订rootScope事件
});
}).controller('ChildCtrl', function($scope) {
$scope.$on("to-parent", function(event, args) {
console.log('child', args);
});
$scope.$on("to-child", function(event, args) {
console.log('child', args);
});
$scope.$on("to-all", function(event, args) {
console.log('child', args);
})
}).controller('BroCtrl', function($scope) {
$scope.$on("to-parent", function(event, args) {
console.log('bro', args);
});
$scope.$on("to-child", function(event, args) {
console.log('bro', args);
});
$scope.$on("to-all", function(event, args) {
console.log('bro', args);
})
})
本文介绍了AngularJS中实现父子控制器间通信的三种方法:通过相同变量的覆盖、声明$rootScope全局变量以及使用broadcast/emit/on等事件广播机制。通过实例展示了如何在不同层级的控制器之间传递消息。
angular里controller跨域传值($rootScope广播事件)&spm=1001.2101.3001.5002&articleId=74907286&d=1&t=3&u=4e2b44f0d4b043e2bea172efe2a17504)
287

被折叠的 条评论
为什么被折叠?



