0

I'm trying since few hours to call a function from a controller to another controller.

I saw similar topics (I tried but I'm certainly too bad): What's the correct way to communicate between controllers in AngularJS? Can one controller call another?

But no concrete example like I'm looking for.

Controllers:

app.controller('Controller1', function($scope, $modal, $modalInstance, job, JobServices) {

   $scope.job1 = function () {
       JobServices.job1($scope.name)
       .success(function(data, status, headers, config) {
          // something
       });
   }


   function doSomething(){
      // How call test() from controller2 ?
   }
}

app.controller('Controller2', function($scope){
   function test(){
      do a lot of things
   }
}

What's the best and easiest way to do that ?

Thank you a lot

EDIT:

I already tried using something like that:

app.controller('Controller1', ['$scope', '$rootScope', function($scope, $rootScope, $modal, $modalInstance, job, JobServices) {

But I have error saying job1 is undefined...

C.Norris
  • 87
  • 1
  • 13
  • You probably want to put your logic into a [service/factory](https://stackoverflow.com/a/28337130/8495123) and call the function on it instead. – Aleksey Solovey Dec 14 '17 at 11:07
  • Possible duplicate of [$on and $broadcast in angular](https://stackoverflow.com/questions/19446755/on-and-broadcast-in-angular) – Sajal Dec 14 '17 at 11:23
  • My problem is I have a lot of errors when I use function($scope, $modal, $modalInstance, job, JobServices) to ['$scope', '$rootscope', function($scope, $rootscope, $modal, $modalInstance, job, JobServices) from my functions like job1 (see my edit) – C.Norris Dec 14 '17 at 13:16

1 Answers1

1

you could the $scope.$emit and $scope.$on, little bit like this

app.controller('Controller1', ['$scope', '$rootScope' function($scope) {
   function doSomething(){
       $rootScope.$emit("callController2", {});
   }
}

app.controller('Controller2', ['$scope', '$rootScope' function($scope) {
  $rootScope.$on("callController2", function(){
    this.test();
  });
  function test(){
    do a lot of things
        }
}
  • As I said upper I already tried that and I have error (saying it's undefined) using ['$scope', '$rootScope'... (see my edit) – C.Norris Dec 14 '17 at 13:35