首页 > 语言 > JavaScript > 正文

AngularJS控制器之间的通信方式详解

2024-05-06 15:07:31
字体:
来源:转载
供稿:网友

本文实例讲述了AngularJS控制器之间的通信方式。分享给大家供大家参考,具体如下:

一、利用作用域的继承方式

由于作用域的继承是基于js的原型继承方式,所以这里分为两种情况,当作用域上面的值为基本类型的时候,修改父作用域上面的值会影响到子作用域,反之,修改子作用域只会影响子作用域的值,不会影响父作用域上面的值;如果需要父作用域与子作用域共享一个值的话,就需要用到后面一种,即作用域上的值为对象,任何一方的修改都能影响另一方,这是因为在js中对象都是引用类型。

基本类型

function Sandcrawler($scope) {  $scope.location = "Mos Eisley North";  $scope.move = function(newLocation) {    $scope.location = newLocation;  }}function Droid($scope) {  $scope.sell = function(newLocation) {    $scope.location = newLocation;  }}

html:

<div ng-controller="Sandcrawler">  <p>Location: {{location}}</p>  <button ng-click="move('Mos Eisley South')">Move</button>  <div ng-controller="Droid">    <p>Location: {{location}}</p>    <button ng-click="sell('Owen Farm')">Sell</button>  </div></div>

对象

function Sandcrawler($scope) {  $scope.obj = {location:"Mos Eisley North"};}function Droid($scope) {  $scope.summon = function(newLocation) {    $scope.obj.location = newLocation;  }}

html:

<div ng-controller="Sandcrawler">  <p>Sandcrawler Location: {{location}}</p>  <div ng-controller="Droid">    <button ng-click="summon('Owen Farm')">      Summon Sandcrawler    </button>  </div></div>

二、基于事件的方式

在一般情况下基于继承的方式已经足够满足大部分情况了,但是这种方式没有实现兄弟控制器之间的通信方式,所以引出了事件的方式。基于事件的方式中我们可以里面作用的$on,$emit,$boardcast这几个方式来实现,其中$on表示事件监听,$emit表示向父级以上的作用域触发事件, $boardcast表示向子级以下的作用域广播事件。参照以下代码:

向上传播事件

function Sandcrawler($scope) {  $scope.location = "Mos Eisley North";  $scope.$on('summon', function(e, newLocation) {    $scope.location = newLocation;  });}function Droid($scope) {  $scope.location = "Owen Farm";  $scope.summon = function() {    $scope.$emit('summon', $scope.location);  }}

html:

<div ng-controller="Sandcrawler">  <p>Sandcrawler Location: {{location}}</p>  <div ng-controller="Droid">    <p>Droid Location: {{location}}</p>    <button ng-click="summon()">Summon Sandcrawler</button>  </div></div>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选