angular.module('myApp', [])
.controller('BugController', ['$scope', '$rootScope', '$interval', BugController]);
function BugController($scope, $rootScope, $interval) {
$scope.bugCount = 5;
$scope.message = "Let's fix those bugs!";
$scope.changeBug = function(change, person) {
var oldValue = $scope.bugCount;
var newValue = $scope.bugCount = Math.max(0, $scope.bugCount + change);
if (oldValue !== newValue) {
//$broadcast an event.
//parameters indicate the change in value and who changed it.
$rootScope.$broadcast('bugs-changed', newValue, oldValue, person);
}
};
//Listen for bugs-changed events
//Use the included parameters to identify who caused the value to change.
$scope.$on('bugs-changed', function(event, newValue, oldValue, person) {
$scope.message = person +
' changed bugCount from ' +
oldValue + ' to ' + newValue + '.';
if (newValue > oldValue) {
$scope.message += ' Dang it, ' + person + '!';
}
else {
$scope.message += ' Good job, ' + person + '!';
}
});
//And random bugs pop up over time
$interval(function() {
$rootScope.$broadcast('bugs-changed', $scope.bugCount + 1, $scope.bugCount++, 'Time')
}, 5000);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="BugController">
<div>Bugs: {{bugCount}}</div>
<p>{{message}}</p>
<p>
Alex
<button ng-click="changeBug(1, 'Alex')">Add bug</button>
<button ng-click="changeBug(-1, 'Alex')">Fix bug</button>
</p>
<p>
David
<button ng-click="changeBug(1, 'David')">Add bug</button>
<button ng-click="changeBug(2, 'David')">Fix bug</button>
</p>
</div>
</div>