How to use $ broadcast (), $ emit () and $ on () in AngularJS


I $emit() that $emit() and $broadcast are emitters and $on is an event listener. I'm working with unit tests and I'm not able to access the following function:


(function () {
'use strict';


    .service('EventHandler', EventHandler);

EventHandler.$inject = ['$rootScope', '$location', '$animate', '$state', '$stateParams', '$sanitize', '$q', '$uibModal', 'toastr',
    'storage', 'StorageService', 'LogService', 'LanguageResource', 'LoginService', 'StcpUtilsService', 'DAOService',
    'CSRF', 'Authorization', 'ShortcutService', 'data_login', 'PermissionsService', 'BusinessLogicService', 'DebugMode'

function EventHandler($rootScope, $location, $animate, $state, $stateParams, $sanitize, $q, $uibModal, toastr, storage, StorageService,
                      LogService, LanguageResource, LoginService, StcpUtilsService, DAOService, CSRF,
                      Authorization, ShortcutService, data_login, PermissionsService, BusinessLogicService, Debug) {

    var animate;
    /* = parameters.$animate || $animate; */
    var rootScope;
    /* = parameters.$rootScope || $rootScope; */
    var scope;
    /* = parameters.$scope; */
    var _toastr;
    /* = parameters.toastr || toastr; */
    var _storage;
    /* = parameters.StorageService || StorageService; */
    var location;
    /* = parameters.$location || $location; */
    var log;
    /* = parameters.LogService ? parameters.LogService.log : LogService.log || LogService.log; */
    var language;
    /* = parameters.LanguageResource || LanguageResource; */
    var shortcut;
    var t;
    var dao;
    var DebugMode;

    return {
        initialize: initialize_component,
        onCheckSession: onCheckSessionHandle,
        onLogin: onLoginHandle,
        onLogout: onLogoutHandle,
        onStateChangeError: onStateChangeErrorHandle,
        onHideMenuCheck: onHideMenuCheckHandle,
        onSetInstance: onSetInstanceHandle,
        onRemoveInstance: onRemoveInstanceHandle,
        onGetInstanceName: onGetInstanceNameHandle,
        onGetInstanceId: onGetInstanceIdHandle,
        onGetOperatorLogged: onGetOperatorLoggedHandle,
        onOperatorIsLogged: onOperatorIsLoggedHandle,
        onShakeMenu: onShakeMenuHandle,
        onCheckInstance: onCheckInstanceHandle,
        onSave: onSaveHandle,
        onDelete: onDeleteHandle,
        onInterceptError: onInterceptErrorHandle,
        onChangeOperatorPassword: onChangePasswordHandle,
        onGetTransfer: onGetTransferHandle,
        onOpenChangeModuleDialog: onOpenChangeModuleDialogHandle,
        onChangeSubModule: onChangeSubModuleHandle,
        onDisplaySelectionInstance: onDisplaySelectionInstanceHandle,
        onGetInstances: onGetInstancesHandle,
        onCheckModule: onCheckModuleHandle,
        // onDataToPersist: onDataToPersistHandle

    // function onDataToPersistHandle() { rootScope.$on('dataToPersist', onDataToPersist); }
    function onRemoveInstanceHandle() {
        rootScope.$on('removeInstance', onRemoveInstance);

    function onRemoveInstance(ev, args) {
        onCheckSession(ev, args);

        if (ev.defaultPrevented === false) {
            rootScope.instanceSelected = undefined;
            delete rootScope.displaySelectionInstance;
            delete rootScope.instance_id;
            delete rootScope.instance_name;
    } //...

I'm doing the tests as follows, but I can't test the "onRemoveInstance" function, they told me to apply some emitter so I can access it. And I need to know how to make ev.defaultPrevented false.


describe('Testing EventHandler', function () {

var srv, rootScope, injector, httpBackend, animate, scope, location, loginService, _toastr, _storage, dao, log, language;

beforeEach(inject(function (EventHandler,_$injector_, $rootScope, $httpBackend, $animate, $location, LoginService, toastr, storage, StorageService, LogService, DAOService, LanguageResource) {
  injector = _$injector_;
  srv = EventHandler;
  rootScope = $rootScope;          
  animate = $animate;
  location = $location;
  loginService = LoginService;
  _toastr = toastr;
  _storage = StorageService;
  log = LogService;
  language = LanguageResource;
  dao = DAOService;

      $rootScope: rootScope,
      $animate: animate,
      $scope: $rootScope.$new(),
      $location: location,
      _toastr: toastr,
      _storage: StorageService,
      log: LogService,
      language: LanguageResource,
      dao: DAOService,

//   rootScope.$on('doLogin', null);      

it('testing if the onRemoveInstance function', function(){  
    srv.ev = {defaultPrevented: false}; //testando para ver se da certo      
    rootScope.$emit('removeInstance', srv.onRemoveInstance); 

it('testing if the onChangeSubModule function', function(){        
    rootScope.$emit('changeSubModule', srv.onChangeSubModule);   

If possible can someone give me a real-time example of using all three?


$emit and $broadcast are very similar. As you said, both are for firing something. I'll try to explain it very simply

The $broadcast calls the event for everyone who is "below" it, it would be the children. $emit calls all events with that name. He's a guy who shoots globally.

$on is the listener, so it will be activated when called by an $emit or $broadcast

I don't know what you want to do there in your code, but it would be something like this:

$scope.$on('onRemoveInstance', function(ev, args) {
onCheckSession(ev, args);

        if (ev.defaultPrevented === false) {
            rootScope.instanceSelected = undefined;
            delete rootScope.displaySelectionInstance;
            delete rootScope.instance_id;
            delete rootScope.instance_name;

// Aqui embaixo eu chamo minha função. Essa minha chamada pode ser feita em qualquer lugar do código, inclusive em outro arquivo javascript em um outro controller.

$scope.$emit('onRemoveInstance', $scope.ALGUMACOISA);

As a request, I'm also leaving this Plunker here showing this in practice.

Also, read about $ROOTSCOPE in the official AngularJS documentation

Scroll to Top