How to call a function from another controller in angularjs? [duplicate] How to call a function from another controller in angularjs? [duplicate] angularjs angularjs

How to call a function from another controller in angularjs? [duplicate]


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.


I wouldn't use function from one controller into another. A better approach would be to move the common function to a service and then inject the service in both controllers.


You may use events to provide your data. Code like that:

app.controller('One', ['$scope', function ($scope) {         $scope.parentmethod=function(){                 $scope.$emit('one', res);// res - your data         }    }]);    app.controller('two', ['$scope', function ($scope) {         $scope.$on('updateMiniBasket', function (event, data) {                ...         });                 }]);