Search code examples
angularjscontrollerangularjs-scope

How to call a function from another controller in AngularJS?


I need to call a function in another controller in AngularJS. How can I do this?

Code:

app.controller('One', ['$scope',
    function($scope) {
        $scope.parentmethod = function() {
            // task
        }
    }
]);

app.controller('two', ['$scope',
    function($scope) {
        $scope.childmethod = function() {
            // Here i want to call parentmethod of One controller
        }
    }
]);

Solution

  • Communication between controllers is done though $emit + $on / $broadcast + $on methods.

    So in your case you want to call a method of Controller "One" inside Controller "Two", the correct way to do this is:

    app.controller('One', ['$scope', '$rootScope'
        function($scope) {
            $rootScope.$on("CallParentMethod", function(){
               $scope.parentmethod();
            });
    
            $scope.parentmethod = function() {
                // task
            }
        }
    ]);
    app.controller('two', ['$scope', '$rootScope'
        function($scope) {
            $scope.childmethod = function() {
                $rootScope.$emit("CallParentMethod", {});
            }
        }
    ]);
    

    While $rootScope.$emit is called, you can send any data as second parameter.