AngularJS:$ emit方法发送重复数据

时间:2018-03-07 09:45:21

标签: javascript angularjs scope broadcast

在我的AngularJS应用程序中,我有三个控制器。一个是主控制器,另外两个是兄弟姐妹。

我有Sibling control 1Main control发送数据,广播数据,然后sibling control 2接收数据。

兄弟控制1

$scope.selectedPatentFx;

$scope.$watch('selectedPatentFx', function(newValue, oldValue){ 
    if($scope.selectedPatentFx) {
       $scope.$emit('calculateFx', {patentfx: newValue});       
    }
})

主要控件

$scope.$on('calculateFx', function(event, obj){
    $scope.$broadcast('calculateFxBroadcast', {fx: obj})
}); 

兄弟控制2

$scope.$on('calculateFxBroadcast', function(event, obj){
   //handle obj
})

问题是数据被发送两次。但是它不会导致任何错误(截至目前)。

问题

为什么数据会被发射/广播两次?

1 个答案:

答案 0 :(得分:1)

我会避免在这里使用事件($broadcast)。您可以使用共享数据的服务来完成此操作。我创建了一个抽象示例,为您提供基本处理。

<强>&GT;通过控制器之间的服务共享数据 - demo fiddle

视图

<div ng-controller="MyCtrl">
  <button ng-click="setData()">
        Set data
      </button>
  <h1>
    Controller1
  </h1>
  <hr>
  <p>
    {{data.getContactInfo()}}
  </p>
</div>
<div ng-controller="MyOtherCtrl">
  <br><br>
  <h1>
    Controller2
  </h1>
  <hr> {{data.getContactInfo()}}
</div>

AngularJS应用程序

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope, myService) {

  $scope.data = myService;

  $scope.setData = function() {
    myService.setContactInfo('Hello World');
  }
});

myApp.controller('MyOtherCtrl', function($scope, myService) {
  $scope.data = myService;
});


myApp.service('myService', function() {
    this.contactInfo = '';

    this.setContactInfo = function (data) {
        this.contactInfo = data;
    }

    this.getContactInfo = function () {
        return this.contactInfo;
    }
});
相关问题