heidsoft / cloud-bigdata-book

write book
56 stars 33 forks source link

angular controller通信问题 #16

Closed heidsoft closed 7 years ago

heidsoft commented 7 years ago

http://stackoverflow.com/questions/9293423/can-one-controller-call-another

heidsoft commented 7 years ago

var myModule = angular.module('myModule', []); myModule.factory('mySharedService', function($rootScope) { var sharedService = {};

sharedService.message = '';

sharedService.prepForBroadcast = function(msg) { this.message = msg; this.broadcastItem(); };

sharedService.broadcastItem = function() { $rootScope.$broadcast('handleBroadcast'); };

return sharedService; });

function ControllerZero($scope, sharedService) { $scope.handleClick = function(msg) { sharedService.prepForBroadcast(msg); };

$scope.$on('handleBroadcast', function() { $scope.message = sharedService.message; });
}

function ControllerOne($scope, sharedService) { $scope.$on('handleBroadcast', function() { $scope.message = 'ONE: ' + sharedService.message; });
}

function ControllerTwo($scope, sharedService) { $scope.$on('handleBroadcast', function() { $scope.message = 'TWO: ' + sharedService.message; }); }

ControllerZero.$inject = ['$scope', 'mySharedService'];

ControllerOne.$inject = ['$scope', 'mySharedService'];

ControllerTwo.$inject = ['$scope', 'mySharedService'];

heidsoft commented 7 years ago

http://stackoverflow.com/questions/28959553/relation-between-two-controller-in-angular

heidsoft commented 7 years ago

已初步解决,在同级controller之间需要使用$rootScope