Angular Events - $broadcast and $emit

A simple example of sending data around, not a best practice by any means. Data-binding is what all the cool kids are doing!

by Himanshu Joshi

HTML

<div ng-app="eventsApp">
    <ul ng-controller="parentController">
        <li>
            <strong ng-click="tellChildren()">{{name}}</strong>
            <input ng-hide="childMessage" ng-model="parentMessage" />{{childMessage}}
            <ul>
                <li class="child" ng-controller="child0Controller"><strong ng-click="tellParents()">{{name}}</strong> - {{parentMessage}}</li>
                <li class="child" ng-controller="child1Controller"><strong ng-click="tellParents()"> {{name}}</strong> - {{parentMessage}}</li>
            </ul>
        </li>
    </ul>
</div>

JavaScript

var app = angular.module('eventsApp', ['eventsApp.controllers']);

var controllers = angular.module('eventsApp.controllers', []);

controllers.controller('parentController', ['$scope', function ($scope) {
    $scope.name = 'parent';
    $scope.message = '';
    $scope.$on('CHILD_DID_IT', function () {
        $scope.childMessage = 'message from the child'
    });
    $scope.tellChildren = function () {
        $scope.$broadcast('PARENT_DID_IT');
    };
}]);


controllers.controller('child0Controller', ['$scope', function ($scope) {
    $scope.name = 'child0';
    $scope.tellParents = function () {
        $scope.$emit('CHILD_DID_IT');
    };
    $scope.notify = function (data) {
        console.log(data)
        alert(data)
    };
    $scope.$on('PARENT_DID_IT', function (e, msg, a) {

        $scope.notify(msg);
    });
}]);
controllers.controller('child1Controller', ['$scope', function ($scope) {
    $scope.name = 'child1';
}]);