AngularJS:$ emit方法发送重复数据 [英] AngularJS: $emit method sending duplicate data

查看:294
本文介绍了AngularJS:$ emit方法发送重复数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的AngularJS应用中,我有三个控制器。一个是主控制器,另外两个是同级兄弟。

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

我有同级控件1 可以将数据发送到主控件,它广播数据,然后由同级控件2 接收。

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

同级控件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
})

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

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?

推荐答案

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

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

<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应用程序



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

这篇关于AngularJS:$ emit方法发送重复数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆