AngularJS - Communication Between Controllers
Using Angular Service to communicate between a textarea in one controller and a div contents in another.
by orlenko
HTML
<div ng-controller="SourceController">
<textarea ng-model="message" ng-change="propagate()"></textarea>
</div>
<div ng-controller="DestinationController">
<div>{{message}}</div>
</div>
JavaScript
var myModule = angular.module('myModule', []);
myModule.factory('MessageSharing', function ($rootScope, $log) {
var share = {};
share.message = '';
share.broadcast = function (msg) {
$log.log('broadcasting ' + msg);
this.message = msg;
this.broadcastItem();
};
share.broadcastItem = function () {
$log.log('broadcasting this ' + this.message);
$rootScope.$broadcast('handleBroadcast');
};
return share;
});
function SourceController($scope, $log, MessageSharing) {
$log.log('Initializing SourceController');
$scope.message = '';
$scope.propagate = function () {
$log.log('Propagating ' + $scope.message);
MessageSharing.broadcast($scope.message);
};
}
function DestinationController($scope, $log, MessageSharing) {
$log.log('Initializing DestinationController');
$scope.message = '';
$scope.$on('handleBroadcast', function () {
$log.log('Got the message: ' + MessageSharing.message);
$scope.message = MessageSharing.message;
});
}