Monday, 6 June 2016

How to call the method which is present inside a another controller IN Angular JS

In this post we are going to see how to call the method which is present inside a another controller, In that it is separate in to two ways downwards and upwards from the controller.$broadcast a method means we are calling a method downwards from the mention scope, if the corresponding method is found then the method present in any controller can be executed, we can pass the data also in broadcast.

1. $broadcast a method from parent controller to the child controller using scope.Why normally we are using the scope in this broadcast, because we are going to call a controller which present as child controller for current controller. so we are setting the place from where to broadcast and which is the shortest one to reach soon., even we can broadcast from the rootScope also. it will broadcast the data.

locapp.controller('childController', function ($scope, $rootScope) {

$scope.employees = [];

$scope.$on('getEmployees', function (evt, data) {

angular.forEach(data, function (item) {

$scope.employees.push(item)

});

});

});

Now the childController is present inside the parentController, so we are broadcast a method getEmployees from the Parent controller along with data from the method getData in parentController. In childController we are having the getEmployees method in $on, the call back have a first argument which is event, second argument is a data supplied from the $broadcast.Here we are using the $scope to $broadcast because the method is present inside a child controller or inside the same scope there is another scope.

Output:

2. $broadcast a method from controller to sibling controller or any controller using the $rootScope.Normally if we want a method to call from another controller which is not present inside our controller, may be present as sibling or present in some where hierarchy, To call a method which is present somewhere else, then we can broadcast a method from the rootScope