父controller 与 子controller 有相同的变量 , 则优先使用子controller的变量 。若子controller没有,则往上查找。类似于js的作用链
app.run 可声明全局变量 $rootScope 语法:
var app = angular.module("apps", []).run(["$rootScope", function($rootScope) { $rootScope.text = []; (注意,在controller里用的时候需要传入 $rootScope 服务,此服务由ng模块生成。) }]);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); }) })