angularJS中的父子作用域和兄弟作用域,以及父子,兄弟controller通信机制

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中除了自定义广播,也可以尝试用生命周期广播解决我们的业务需求。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值