发送和广播功能交换输入值不起作用

时间:2015-12-07 11:56:35

标签: angularjs emit

我正在尝试使用广播按预期工作将父控制器$scope值更新为子控制器$scope值,但在尝试将子$scop e值更新为父级时不会更新发射函数的$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>
&#13;
&#13;
&#13;

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

1 个答案:

答案 0 :(得分:0)

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