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...

3
  • You probably want to put your logic into a service/factory and call the function on it instead. Commented Dec 14, 2017 at 11:07
  • Possible duplicate of $on and $broadcast in angular Commented Dec 14, 2017 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) Commented Dec 14, 2017 at 13:16

1 Answer 1

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
        }
}
Sign up to request clarification or add additional context in comments.

1 Comment

As I said upper I already tried that and I have error (saying it's undefined) using ['$scope', '$rootScope'... (see my edit)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.