Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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('Controller1',function($scope,$http,$compile){
    $scope.test1=function($scope)
    {
          alert("test1");
    }
});

app.controller('Controller2',function($scope,$http,$compile){
    $scope.test2=function($scope)
    {
          alert("test1");
    }
});
app.controller('Controller3',function($scope,$http,$compile){
  ///
});

Now i want to call test2 function inside controller3. Can anybody help.. Thanks in Avance... :)

like image 338
Mayur Avatar asked Aug 29 '14 06:08

Mayur


People also ask

How to call function of another controller in AngularJS?

If the two controller is nested in One controller. Then you can simply call: $scope. parentmethod();

What is rootScope broadcast in AngularJS?

$broadcast in AngularJS? The $rootScope. $broadcast is used to broadcast a “global” event that can be caught by any listener of that particular scope. The descendant scopes can catch and handle this event by using $scope.

What is service in AngularJS?

In AngularJS, a service is a function, or object, that is available for, and limited to, your AngularJS application. AngularJS has about 30 built-in services.


1 Answers

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

like image 68
RSquared Avatar answered Oct 13 '22 06:10

RSquared