JSFiddle - React, Tailwind, and code Playground
by Danish Farman
HTML
<body ng-app="myModule">
<div ng-controller="ControllerOne">
<input type="text" ng-model="message" />
<button ng-click="handleClick(message)">BROADCAST</button>
</div>
<div ng-controller="ControllerTwo">
<input type="text" ng-model="message" />
</div>
<div ng-controller="ControllerThree">
<input type="text" ng-model="message" />
</div>
</body>
JavaScript
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 ControllerOne($scope) {
$scope.handleClick = function (msg) {
mySharedService.prepForBroadCast(msg);
};
$scope.$on('handleBroadcast', function () {
$scope.message = 'ONE: ' + mySharedService.message;
});
}
function ControllerTwo($scope) {
$scope.$on('handleBroadcast', function () {
$scope.message = 'TWO: ' + mySharedService.message;
});
}
function ControllerThree($scope) {
$scope.$on('handleBroadcast', function () {
$scope.message = 'THREE: ' + mySharedService.message;
});
}
ControllerOne.$inject = ['$scope', 'mySharedService'];
ControllerTwo.$inject = ['$scope', 'mySharedService'];
ControllerThree.$inject = ['$scope', 'mySharedService'];