【问题标题】:Emit and Broadcast functon exchanging the input value not working发射和广播功能交换输入值不起作用
【发布时间】:2015-12-07 11:56:34
【问题描述】:

我正在尝试使用广播按预期工作将父控制器 $scope 值更新为子控制器 $scope 值,但在尝试通过发射将子 $scope 值更新为父 $scope 值时未更新功能。这是我的代码:

app.controller('FirstCtrl', function($rootScope, $scope) {
  $scope.firstRegister = function() {
    $rootScope.$broadcast('broadcast', $scope.name)
  };


  $scope.$on('emit', function(events, args) {
    $scope.name = args;

  });

});

app.controller('SecondCtrl', function($rootScope, $scope) {
  $scope.$on('broadcast', function(events, args) {
    $scope.name = args;
  });

  $scope.secondRegister = function() {
    $rootScope.$emit('emit', $scope.name)
  };
  
<div ng-controller="FirstCtrl" class="ng-scope">
<input ng-model="name" />
<button ng-click="firstRegister()">Parent</button>

<div ng-controller="SecondCtrl" class="ng-scope">
  <input ng-model="name" />
  <button ng-click="secondRegister()">Child</button>
</div>

</div>

plnkr 链接:http://plnkr.co/edit/l9qD0ZO4MptnWx6u3U9c?p=preview

【问题讨论】:

  • 为什么不使用service/factory 而不是这种事件驱动的方法..?
  • 这似乎是一种复杂的方法。使用服务在控制器之间进行通信。你也可以(虽然不推荐)只在控制器的根作用域上设置值——那么为什么要使用广播模式呢?
  • 只有 $scope 值必须根据我的要求在父控制器和子控制器之间交换,以便我尝试使用事件方法(广播和发射)。我可以从我的代码中知道问题吗?
  • 您不应该以这种方式使用 $rootscope - 通常 99% 的情况下使用 $rootscope 作为存储/共享机制是错误的。它很懒。服务/工厂就是为了这个目的而存在的,并且可以注入到其他需要这种依赖关系的地方。

标签: angularjs emit


【解决方案1】:

我在rootscope 中广播/发射事件然后在rootscope 中捕获相同的事件。这是工作的plunkr 可以看到click on this link

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


app.controller('FirstCtrl', function($rootScope, $scope) {
  $scope.firstRegister = function() {
    $rootScope.$broadcast('broadcast', $scope.name)
  };


  $rootScope.$on('emit', function(events, args) {
    $scope.name = args;
  });

});

app.controller('SecondCtrl', function($rootScope, $scope) {
  $rootScope.$on('broadcast', function(events, args) {
    $scope.name = args;
  });

  $scope.secondRegister = function($event) {
    $rootScope.$emit('emit', $scope.name)
  } ;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多