# AngularJS - Events ## Lesson Objectives 1. Describe situations where communicating between controllers is difficult 1. Send and receive an event ## Describe situations where communicating between controllers is difficult - We want to modularize our code, so that when a controller performs an action, it can notify all of its ancestors/descendants - This allows a developer to work on his/her specific module, without worrying about what's going on around them - When elements with controllers are being created dynamically, knowing a controller's ancestors/descendants can become difficult. ## Send and receive an event To send a message down to your descendant controllers: ```javascript $scope.$broadcast('eventName', { message: msg }); ``` To send a message up to your ancestor controllers: ```javascript $scope.$emit('eventName', { message: msg }); ``` To receive a message sent by another controller: ```javascript $scope.$on('eventName', function (event, data) { //do stuff here }); ``` ## Examples ### Broadcast file: index.html ```html

Hi

Click to Send Message
``` file: js/app.js ```javascript const app = angular.module('MyApp', []); app.controller('ParentCtrl', ['$scope', function($scope){ this.sendMessage = function(){ $scope.$broadcast('eventName', { someProperty:'somevalue' }); } }]); app.controller('ChildCtrl', ['$scope', function($scope){ $scope.$on('eventName', function(event, data){ console.log(data); }); }]); ``` ### Emit file: index.html ```html

Hi

Click Me
``` file: js/app.js ```javascript const app = angular.module('MyApp', []); app.controller('ParentCtrl', ['$scope', function($scope){ $scope.$on('eventName', function(event, data){ console.log(data); }); }]); app.controller('ChildCtrl', ['$scope', function($scope){ this.sendMessage = function(){ $scope.$emit('eventName', { someProperty:'somevalue' }); } }]); ```