$emit, $broadcast, $on – Part1

How to use $rootScope:

As we know that $rootScope is the parent for $scope, to override the $rootScope we need to re-initialize the $rootScope variable with $scope

Let us see an example

In this example we have injected $rootScope in both parent and child controllers.

As $rootScope variables will be available throughout the application we can now access the $rootScope variable anywhere in the application by just injecting the $rootScope

Output:

  • Now if we remove the $rootScope from Parent and initialize it in child controller, it works same.

Output:

How to pass data from parent controller to child

To pass the data from Parent Controller to Child, we need to extract parent controller $scope variable using $parent.

Example: In this example we will use only $scope.

How to pass data from child controller to parent

To pass data from child to parent controllers using $scope we don’t have $child to take from child controller. But here I’ll show you one of the possible way to transfer data.

  • In child controller initialize the empName in an object as $scope.employee.empName.
  • In parent controller declare an empty object naming with same object as $scope.employee = {}

Output:

$emit, $broadcast, $on – Part2

One thought to “$emit, $broadcast, $on – Part1”

Leave a Reply

Your email address will not be published. Required fields are marked *