1

I have a page that uses two controllers. One is associated with the header (which is reused on many different pages) and the other is associated with the body of the page. The mark-up looks something like:

<div id = 'header' ng-controller = 'headerController' >
    <div id = 'login-button' ng-click = 'login()'>
        Login
    </div>
</div>

<div id = 'body' ng-controller = 'myPageController'>
     ....
</div>

The controllers are defined in two separate JS files respectively:

headerController.js
myPageController.js

I would like to bind a listener to the login() function so that whenever the button associated with it is clicked, another function is called in the myPageController.js file.

How would I go about doing this in Angular?

Lloyd Banks
  • 35,740
  • 58
  • 156
  • 248

2 Answers2

5

Probably the best way is to $broadcast() an event from the $rootScope that your page controller handles using $scope.$on().

Example:

headerController.js:

function headerController($scope, $rootScope) {
     $scope.login = function () {
         $rootScope.$broadcast('login');
     };
}

myPageController.js

function myPageController($scope) {
    $scope.$on('login', function () {
        // handle login event here
    });
}
GregL
  • 37,147
  • 8
  • 62
  • 67
0

$rootScope.$broadcast() is fairly slow. If you just want two unrelated controllers to communicate, this is best done through a service. For example, see my answer at:

Communicating between a Multiple Controllers and a directive

Hope that helps!

Community
  • 1
  • 1
Robert Balicki
  • 1,583
  • 2
  • 16
  • 24