angularJS中非常重要的概念之一就是作用域,不同的作用域之间是相互隔离的,通过常规手段是无法互相访问变量及方法的
本次我们着重讲一下父子作用域和兄弟作用域
1.父子作用域
<div ng-controller="ParentCtrl"> <div ng-controller="ChildCtrl"></div> </div>
当我们的controller层级关系是这种时,ChildCtrl就是子controller,ParentCtrl就是父controller,他们之间的作用域关系就是父子作用域
app.controller("ParentCtrl", [ '$scope', function($scope){ $scope.title = "I'm the Parent."; }]); app.controller("ChildCtrl", [ '$scope', function($scope){ $scope.title = "I'm the Child."; }]);
此时父子controller中都有$scope.title这个变量,此时如果子controller想使用父作用域中的变量的话:
$scope.$parent.title="Get parent's title";
如果反过来,父controller想访问子controller中的变量或方法的话:
$scope.$$childHead.title="Get the first child's title"; //得到第一个子作用域中的变量 $scope.$$childTail.title="Get the last child;s title";//得到最后一个子作用域中的变量
这里要特殊说一点,父controller可以有很多个子controller,但是一个子controller只能有一个父controller,一个controller可以有很多个
兄弟controller
2.兄弟作用域
<div ng-controller="FirstCtrl"></div> <div ng-controller="SecondCtrl"></div>
此时FirstCtrl和SecondCtrl是兄弟关系,如果在FirstCtrl中想访问SecondCtrl中的变量或方法的话:
$scope.$$nextSibling.title="Get little brother's title";
如果在SecondCtrl中想访问FirstCtrl中的变量的话:
$scope.$$prevSibling.title="Get big brother's title";
以上就是简单的父子,兄弟作用域相互访问
除了简单的作用域访问外,angularJS中的controller间通信机制大家已经很清楚了,但是兄弟之间的正确通信方式,大家真的清楚吗?
3.controller通信
还是以这段代码为例
<div ng-controller="FirstCtrl"></div> <div ng-controller="SecondCtrl"></div>
兄弟controller这种关系在ionic路由中是非常常见的,比如某列表界面跳转到其详情界面,二者就是兄弟关系(注意:不是父子关系)
app.controller("FirstCtrl", [ '$scope', '$rootScope', function($scope, $rootScope){ $rootScope.$on("pong", function(e, time){ $scope.time = time; }); $scope.ping = function(){ $rootScope.$broadcast("ping"); }; }]); app.controller("SecondCtrl", [ '$scope', function($scope){ $scope.$on("ping", function(e, time){ $scope.time = time; }); $scope.pong = function(){ $scope.$emit("pong", new Date()); }; }]);
根据上面这段代码,我们可见,FirstCtrl和SecondCtrl两个兄弟controller,从前者到后者,通信要用$rootScope进行$broadcast(),接收从SecondCtrl的广播,使用$rootScope.$on()即可;而在SecondCtrl中,接收来自FirstCtrl的广播,使用$scope.$on(),发送广播进行通信,使用$scope.$emit(),这才是标准的兄弟controller之间进行广播通信的方式
angularJS的广播机制一直都因为使用$rootScope导致全局污染以及广播频繁使用导致性能下降而存在争议,我们在设计功能时,尽可能在必需的时候,再使用这种自定义广播,ionic中除了自定义广播,也可以尝试用生命周期广播解决我们的业务需求。