Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
2 views
in Web Technology by (47.6k points)

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.

1 Answer

+2 votes
by (106k points)

Yes, there are many ways to communicate with controllers. The best way would be sharing service to see the code below:-

function FirstController(someDataService) {

function SecondController(someDataService) {

}

The second way is emitting an event on scope see the code below:-

function FirstController($scope) { 

$scope.$on('someEvent', function(event, args) {}); 

}

function SecondController($scope) {

$scope.$emit('someEvent', args); 

}

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...