Search code examples
javascriptangularjsdependency-injectionangularjs-scopeangularjs-controller

AngularJS: Inject controller inside another controller from the same module


Is possible to inject a controller into another controller that is part of the same module?

example:

var app = angular.module('myAppModule', [])
.controller('controllerOne', ['$scope', function($scope){
  $scope.helloWorld = function(){
    return 'Hello World';
  }
}])
.controller('controllerTwo', ['$scope', 'controllerOne', function($scope, controllerOne){
  console.log(controllerOne.helloWorld());
}])

I keep getting unknown provider on controllerOne. I don't see how that's possible since they coexist in the same module. Any help would be much appreciated.


Solution

  • You need to use $controller dependency by using that you can inject one controller to another

    .controller('controllerTwo', ['$scope', '$controller', function($scope, $controller){
      $controller('controllerOne', {$scope: $scope})
      //inside scope you the controllerOne scope will available
    }]);
    

    But do prefer service/factory to share data