How do I inject a controller into another controller in AngularJS How do I inject a controller into another controller in AngularJS angularjs angularjs

How do I inject a controller into another controller in AngularJS


If your intention is to get hold of already instantiated controller of another component and that if you are following component/directive based approach you can always require a controller (instance of a component) from a another component that follows a certain hierarchy.

For example:

//some container component that provides a wizard and transcludes the page components displayed in a wizardmyModule.component('wizardContainer', {  ...,  controller : function WizardController() {    this.disableNext = function() {       //disable next step... some implementation to disable the next button hosted by the wizard    }  },  ...});//some child componentmyModule.component('onboardingStep', { ..., controller : function OnboadingStepController(){    this.$onInit = function() {      //.... you can access this.container.disableNext() function    }    this.onChange = function(val) {      //..say some value has been changed and it is not valid i do not want wizard to enable next button so i call container's disable method i.e      if(notIsValid(val)){        this.container.disableNext();      }    } }, ..., require : {    container: '^^wizardContainer' //Require a wizard component's controller which exist in its parent hierarchy. }, ...});

Now the usage of these above components might be something like this:

<wizard-container ....><!--some stuff-->...<!-- some where there is this page that displays initial step via child component --><on-boarding-step ...> <!--- some stuff--></on-boarding-step>...<!--some stuff--></wizard-container>

There are many ways you can set up require.

(no prefix) - Locate the required controller on the current element. Throw an error if not found.

? - Attempt to locate the required controller or pass null to the link fn if not found.

^ - Locate the required controller by searching the element and its parents. Throw an error if not found.

^^ - Locate the required controller by searching the element's parents. Throw an error if not found.

?^ - Attempt to locate the required controller by searching the element and its parents or pass null to the link fn if not found.

?^^ - Attempt to locate the required controller by searching the element's parents, or pass null to the link fn if not found.



Old Answer:

You need to inject $controller service to instantiate a controller inside another controller. But be aware that this might lead to some design issues. You could always create reusable services that follows Single Responsibility and inject them in the controllers as you need.

Example:

app.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {   var testCtrl1ViewModel = $scope.$new(); //You need to supply a scope while instantiating.   //Provide the scope, you can also do $scope.$new(true) in order to create an isolated scope.   //In this case it is the child scope of this scope.   $controller('TestCtrl1',{$scope : testCtrl1ViewModel });   testCtrl1ViewModel.myMethod(); //And call the method on the newScope.}]);

In any case you cannot call TestCtrl1.myMethod() because you have attached the method on the $scope and not on the controller instance.

If you are sharing the controller, then it would always be better to do:-

.controller('TestCtrl1', ['$log', function ($log) {    this.myMethod = function () {        $log.debug("TestCtrl1 - myMethod");    }}]);

and while consuming do:

.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {     var testCtrl1ViewModel = $controller('TestCtrl1');     testCtrl1ViewModel.myMethod();}]);

In the first case really the $scope is your view model, and in the second case it the controller instance itself.


I'd suggest the question you should be asking is how to inject services into controllers. Fat services with skinny controllers is a good rule of thumb, aka just use controllers to glue your service/factory (with the business logic) into your views.

Controllers get garbage collected on route changes, so for example, if you use controllers to hold business logic that renders a value, your going to lose state on two pages if the app user clicks the browser back button.

var app = angular.module("testApp", ['']);app.factory('methodFactory', function () {    return { myMethod: function () {            console.log("methodFactory - myMethod");    };};app.controller('TestCtrl1', ['$scope', 'methodFactory', function ($scope,methodFactory) {  //Comma was missing here.Now it is corrected.    $scope.mymethod1 = methodFactory.myMethod();}]);app.controller('TestCtrl2', ['$scope', 'methodFactory', function ($scope, methodFactory) {    $scope.mymethod2 = methodFactory.myMethod();}]);

Here is a working demo of factory injected into two controllers

Also, I'd suggest having a read of this tutorial on services/factories.


There is no need to import/Inject your controller in JS. You can just inject your controller/nested controller through your HTML.It's worked for me.Like :

<div ng-controller="TestCtrl1">    <div ng-controller="TestCtrl2">      <!-- your code-->     </div> </div>