Search code examples
angularjsangularjs-scopebroadcastangularjs-controllerangularjs-rootscope

Change child scope using broadcast from app.run


I have an angular app with the name DemoProject.

I have an app.run controller and one child controller

JS

var app = angular.module("DemoProject", ['ngRoute', 'ngAnimate', 'ngMessages', 'ngMaterial']);

app.run(function ($rootScope, $route, $location, $mdDialog) {
    $rootScope.validate = true;

    $rootScope.$broadcast('eventName', { myName: 'Bala' });

});

app.controller('ChildController', function ($scope, $location, $rootScope, $document, $window) {
    $scope.myName = '';
});

I can't update the child controller scope using broadcast.


Solution

  • app.controller('ChildController', function ($scope, $location, $rootScope, $document, $window) {
      $scope.myName = '';
    
      $rootScope.$on('eventName', function(event, args){
          console.log(args);
          $scope.myName = args.myName;
      });
    });