Call a controller from another controller in AngularJS

Whenever you want to share some data between AngularJS controllers or whenever you want to pass some data from one controller to other controller, then you can communicate between controllers in multiple ways.

By Sharing a Service:


You can share a common service between two controllers.

consider you have the following service called 'myService' which returns an array like below.

var myApp = angular.module('myApp', []);
 
myApp.factory('myService'function () {
    return []; //return an array
});

Now you can use this service in your AngularJS controllers like below

function FirstController(myService) {
    //your code here
}
 
function SecondController(myService) {
    //your code here
}

you can also define methods in the service and you can call those methods from controllers.

By Emitting an Event ($emit):


You can dispatch an event using $emit from one controller and you can listen to that event using $on from other controller.

Example:

function FirstController($scope) {
    $scope.$on('someEvent'function (event, args) {
    });
    // this is another controller or even directive
}
 
function SecondController($scope) {
    $scope.$emit('someEvent', args);
}
here orgs means Optional set of arguments which will be passed onto the event listeners.

In this way you can communicate between the controllers in AngularJS.

For more posts on angularJS visit: AngularJS


2 comments: