Javascript – Can one AngularJS controller call another

angularjshtmljavascript

Is it possible to have one controller use another?

For example:

This HTML document simply prints a message delivered by the MessageCtrl controller in the messageCtrl.js file.

<html xmlns:ng="http://angularjs.org/">
<head>
    <meta charset="utf-8" />
    <title>Inter Controller Communication</title>
</head>
<body>
    <div ng:controller="MessageCtrl">
        <p>{{message}}</p>
    </div>

    <!-- Angular Scripts -->
    <script src="http://code.angularjs.org/angular-0.9.19.js" ng:autobind></script>
    <script src="js/messageCtrl.js" type="text/javascript"></script>
</body>
</html>

The controller file contains the following code:

function MessageCtrl()
{
    this.message = function() { 
        return "The current date is: " + new Date().toString(); 
    };
}

Which simply prints the current date;

If I were to add another controller, DateCtrl which handed the date in a specific format back to MessageCtrl, how would one go about doing this? The DI framework seems to be concerned with XmlHttpRequests and accessing services.

Best Answer

There are multiple ways how to communicate between controllers.

The best one is probably sharing a service:

function FirstController(someDataService) 
{
  // use the data service, bind to template...
  // or call methods on someDataService to send a request to server
}

function SecondController(someDataService) 
{
  // has a reference to the same instance of the service
  // so if the service updates state for example, this controller knows about it
}

Another way is emitting an event on scope:

function FirstController($scope) 
{
  $scope.$on('someEvent', function(event, args) {});
  // another controller or even directive
}

function SecondController($scope) 
{
  $scope.$emit('someEvent', args);
}

In both cases, you can communicate with any directive as well.