In AngularJS when it comes to communicating between controllers, one would naturally assume to reference another controller you can simply inject it into another controller and call its methods: however, you cannot do that.
Method 1: Shared service
One such method of communicating and sharing methods betweens multiple controllers is a shared service. Here you might put in a method for closing a overlay or redirecting the browser somewhere or checking the state and value of a variable.
The following example assumes you have created a service called “myService” and you have a method called updateVal and getVal for getting and setting values.
var myModule = angular.module('myapp', []);
myModule.controller('myController', ['$scope', 'myService', function ($scope, myService) {
myService.updateVal('name', 'Dwayne');
}]);
myModule.controller('otherController', ['$scope', 'myService', function ($scope, myService) {
if (myService.getVal('name') === 'Dwayne') {
alert('The name is ' + myService.getVal('name'));
} else {
alert('There is no Dwayne');
}
}]);
This is my preferred approach for sharing data and methods between controllers for a number of reasons; it makes things cleaner, it keeps logic separate from your controllers and above all: it makes things easier to test.
Method 2: Events
In some cases, events can be a lot cleaner than using a separate service. Triggering an event say for example when you open up an overlay, close it or perform some action you want to inform other controllers about can be done emitting an event on $scope.
var myModule = angular.module('myapp', []);
myModule.controller('myController', ['$scope', function ($scope) {
$scope.$on('profile-updated', function(event, profileObj) {
// profileObj contains; name, country and email from emitted event
});
}]);
myModule.controller('otherController', ['$scope', function ($scope) {
$scope.$emit('profile-updated', {
name: 'Dwayne',
country: 'Australia',
email: 'somedude@example.com'
});
}]);
Conclusion
Pick whichever feels right. I personally prefer method 1 because as I mentioned, it is testable, it is cleaner and keeps things separate. But using events also have their advantages as well.