AngularJS: $emit method sending duplicate data

2019-07-23 19:24发布

问题:

In my AngularJS app, I have three controllers. One is the main controller and the other two are siblings.

I have Sibling control 1 to emit data to Main control, which broadcasts the data, which sibling control 2 then picks up.

Sibling control 1

$scope.selectedPatentFx;

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

Main control

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

Sibling control 2

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

The issue is that the data is being sent twice. However it doesn't cause any errors (as of yet).

Question

Why is the data being emitted/broadcasted twice?

回答1:

I would avoid using events ($broadcast) here. You can do it by using a service which shares the data. I created an abstract example which delivers you the basic handling.

> Share data via service between controllers - demo fiddle

View

<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 application

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;
    }
});