Skip to content Skip to sidebar Skip to footer

Call Function From Another Controller Angular Js

I am new to using angular js and i have declare many controller and now i want to user function of one controller into another controller. here is my sample code. app.controller('C

Solution 1:

You can't call a method from a controller within a controller. You will need to extract the method out, create a service and call it. This will also decouple the code from each other and make it more testable

(function() {
    angular.module('app', [])
        .service('svc', function() {
            var svc = {};

            svc.method = function() {
                alert(1);
            }

            return svc;
        })
        .controller('ctrl', [
            '$scope', 'svc', function($scope, svc) {
                svc.method();
            }
        ]);
})();

Example: http://plnkr.co/edit/FQnthYpxgxAiIJYa69hu?p=preview

Solution 2:

Best way is write a service and use that service in both controllers. see the documentation Service documentation

If you really want to access controller method from another controller then follow the below option: emitting an event on scope:

functionFirstController($scope) {  $scope.$on('someEvent', function(event, args) {});}

functionSecondController($scope) {  $scope.$emit('someEvent', args);}

Solution 3:

The controller is a constructor, it will create a new instance if for example used in a directive.

You can still do what you wanted, assuming that your controllers are in the same scope, just do:

Note they must be in the same scope, could still work if a child scope was not isolated. The directive's definition:

{
    controller: Controller1,
    controllerAs: 'ctrl1',
    link: function($scope) {

        $scope.ctrl1.test1(); // call a method from controller 1$scope.ctrl2.test2(); // created by the directive after this definition$scope.ctrl3.test3(); // created by the directive after this definition
    }
}

....
{
    controller: Controller2,
    controllerAs: 'ctrl2',
    link: function($scope) {
        $scope.ctrl1.test1(); // created earlier$scope.ctrl2.test2(); // ...$scope.ctrl3.test3(); // created by the directive after this definition
    }
}

....
{
    controller: Controller3,
    controllerAs: 'ctrl3',
    link: function($scope) {
        $scope.ctrl1.test1();
        $scope.ctrl2.test2();
        $scope.ctrl3.test3();
    }
}

This should work.

Post a Comment for "Call Function From Another Controller Angular Js"