如何在控制器之间进行通信?

时间:2014-09-22 18:16:55

标签: angularjs controllers

这是plunker Link

http://plnkr.co/edit/X0fhStczchvxkHMUH9iq?p=preview

var app = angular.module('app', []);
app.Controller('firstCtrl', function ($scope, $rootScope){
$scope.handleClick = function(txt){
$rootScope.$broadcast('someEvent',txt)
}
});

app.Controller('secondCtrl', function ($scope, $rootScope){
$scope.$on('someEvent', function(event, mass) {
  $scope.msg =mass
 });
 });

1 个答案:

答案 0 :(得分:0)

@PSL是正确的。我已将广播添加到按钮单击以显示该功能正常。请注意,数组在输入中显示为字符串“1,2,3”。

<div ng-controller="firstCtrl"><button ng-click="broadcastMass()">Broadcast</button></div>

控制器:

var app = angular.module('app', []);
app.controller('firstCtrl', function firstCtrl($scope, $rootScope){
    $scope.broadcastClick = function() {
      $rootScope.$broadcast('someEvent', [1,2,3]);
    };
});
app.controller('secondCtrl',function secondCtrl($rootScope){
    $rootScope.$on('someEvent', function(event, mass) {
      $rootScope.msg = mass;
    });
});

link to plunker