angular中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中除了自定義廣播,也可以嘗試用生命週期廣播解決我們的業務需求。

發佈了58 篇原創文章 · 獲贊 48 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章