Can one AngularJS controller call another?

JavascriptHtmlAngularjs

Javascript Problem Overview


Is it possible to have one controller use another?

For example:

This HTML document simply prints a message delivered by the MessageCtrl controller in the messageCtrl.js file.

<html xmlns:ng="http://angularjs.org/">
<head>
    <meta charset="utf-8" />
    <title>Inter Controller Communication</title>
</head>
<body>
    <div ng:controller="MessageCtrl">
        <p>{{message}}</p>
    </div>
    
    <!-- Angular Scripts -->
    <script src="http://code.angularjs.org/angular-0.9.19.js" ng:autobind></script>
    <script src="js/messageCtrl.js" type="text/javascript"></script>
</body>
</html>

The controller file contains the following code:

function MessageCtrl()
{
    this.message = function() { 
        return "The current date is: " + new Date().toString(); 
    };
}

Which simply prints the current date;

If I were to add another controller, DateCtrl which handed the date in a specific format back to MessageCtrl, how would one go about doing this? The DI framework seems to be concerned with XmlHttpRequests and accessing services.

Javascript Solutions


Solution 1 - Javascript

There are multiple ways how to communicate between controllers.

The best one is probably sharing a service:

function FirstController(someDataService) 
{
  // use the data service, bind to template...
  // or call methods on someDataService to send a request to server
}

function SecondController(someDataService) 
{
  // has a reference to the same instance of the service
  // so if the service updates state for example, this controller knows about it
}

Another way is emitting an event on scope:

function FirstController($scope) 
{
  $scope.$on('someEvent', function(event, args) {});
  // another controller or even directive
}

function SecondController($scope) 
{
  $scope.$emit('someEvent', args);
}

In both cases, you can communicate with any directive as well.

Solution 2 - Javascript

See this fiddle: http://jsfiddle.net/simpulton/XqDxG/

Also watch the following video: Communicating Between Controllers

Html:

<div ng-controller="ControllerZero">
  <input ng-model="message" >
  <button ng-click="handleClick(message);">LOG</button>
</div>

<div ng-controller="ControllerOne">
  <input ng-model="message" >
</div>

<div ng-controller="ControllerTwo">
  <input ng-model="message" >
</div>

javascript:

var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
  var sharedService = {};

  sharedService.message = '';

  sharedService.prepForBroadcast = function(msg) {
    this.message = msg;
    this.broadcastItem();
  };

  sharedService.broadcastItem = function() {
    $rootScope.$broadcast('handleBroadcast');
  };

  return sharedService;
});

function ControllerZero($scope, sharedService) {
  $scope.handleClick = function(msg) {
    sharedService.prepForBroadcast(msg);
  };
    
  $scope.$on('handleBroadcast', function() {
    $scope.message = sharedService.message;
  });        
}

function ControllerOne($scope, sharedService) {
  $scope.$on('handleBroadcast', function() {
    $scope.message = 'ONE: ' + sharedService.message;
  });        
}

function ControllerTwo($scope, sharedService) {
  $scope.$on('handleBroadcast', function() {
    $scope.message = 'TWO: ' + sharedService.message;
  });
}

ControllerZero.$inject = ['$scope', 'mySharedService'];        
    
ControllerOne.$inject = ['$scope', 'mySharedService'];

ControllerTwo.$inject = ['$scope', 'mySharedService'];

Solution 3 - Javascript

If you want to call one controller into another there are four methods available

  1. $rootScope.$emit() and $rootScope.$broadcast()
  2. If Second controller is child ,you can use Parent child communication .
  3. Use Services
  4. Kind of hack - with the help of angular.element()

> 1. $rootScope.$emit() and $rootScope.$broadcast()

Controller and its scope can get destroyed, but the $rootScope remains across the application, that's why we are taking $rootScope because $rootScope is parent of all scopes .

If you are performing communication from parent to child and even child wants to communicate with its siblings, you can use $broadcast

If you are performing communication from child to parent ,no siblings invovled then you can use $rootScope.$emit

HTML

<body ng-app="myApp">
    <div ng-controller="ParentCtrl" class="ng-scope">
      // ParentCtrl
      <div ng-controller="Sibling1" class="ng-scope">
        // Sibling first controller
      </div>
      <div ng-controller="Sibling2" class="ng-scope">
        // Sibling Second controller
        <div ng-controller="Child" class="ng-scope">
          // Child controller
        </div>
      </div>
    </div>
</body>

Angularjs Code

 var app =  angular.module('myApp',[]);//We will use it throughout the example 
    app.controller('Child', function($rootScope) {
      $rootScope.$emit('childEmit', 'Child calling parent');
      $rootScope.$broadcast('siblingAndParent');
    });

app.controller('Sibling1', function($rootScope) {
  $rootScope.$on('childEmit', function(event, data) {
    console.log(data + ' Inside Sibling one');
  });
  $rootScope.$on('siblingAndParent', function(event, data) {
    console.log('broadcast from child in parent');
  });
});

app.controller('Sibling2', function($rootScope) {
  $rootScope.$on('childEmit', function(event, data) {
    console.log(data + ' Inside Sibling two');
  });
  $rootScope.$on('siblingAndParent', function(event, data) {
    console.log('broadcast from child in parent');
  });
});

app.controller('ParentCtrl', function($rootScope) {
  $rootScope.$on('childEmit', function(event, data) {
    console.log(data + ' Inside parent controller');
  });
  $rootScope.$on('siblingAndParent', function(event, data) {
    console.log('broadcast from child in parent');
  });
});

In above code console of $emit 'childEmit' will not call inside child siblings and It will call inside only parent, where $broadcast get called inside siblings and parent as well.This is the place where performance come into a action.$emit is preferrable, if you are using child to parent communication because it skips some dirty checks.

> 2. If Second controller is child, you can use Child Parent communication

Its one of the best method, If you want to do child parent communication where child wants to communicate with immediate parent then it would not need any kind $broadcast or $emit but if you want to do communication from parent to child then you have to use either service or $broadcast

For example HTML:-

<div ng-controller="ParentCtrl">
 <div ng-controller="ChildCtrl">
 </div>
</div>

Angularjs

 app.controller('ParentCtrl', function($scope) {
   $scope.value='Its parent';
      });
  app.controller('ChildCtrl', function($scope) {
   console.log($scope.value);
  });

Whenever you are using child to parent communication, Angularjs will search for a variable inside child, If it is not present inside then it will choose to see the values inside parent controller.

>3.Use Services

AngularJS supports the concepts of "Seperation of Concerns" using services architecture. Services are javascript functions and are responsible to do a specific tasks only.This makes them an individual entity which is maintainable and testable.Services used to inject using Dependency Injection mecahnism of Angularjs.

Angularjs code:

app.service('communicate',function(){
  this.communicateValue='Hello';
});

app.controller('ParentCtrl',function(communicate){//Dependency Injection
  console.log(communicate.communicateValue+" Parent World");
});

app.controller('ChildCtrl',function(communicate){//Dependency Injection
  console.log(communicate.communicateValue+" Child World");
});

It will give output Hello Child World and Hello Parent World . According to Angular docs of services Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.

> 4.Kind of hack - with the help of angular.element()

This method gets scope() from the element by its Id / unique class.angular.element() method returns element and scope() gives $scope variable of another variable using $scope variable of one controller inside another is not a good practice.

HTML:-

<div id='parent' ng-controller='ParentCtrl'>{{varParent}}
 <span ng-click='getValueFromChild()'>Click to get ValueFormChild</span>
 <div id='child' ng-controller='childCtrl'>{{varChild}}
   <span ng-click='getValueFromParent()'>Click to get ValueFormParent </span>
 </div>
</div>

Angularjs:-

app.controller('ParentCtrl',function($scope){
 $scope.varParent="Hello Parent";
  $scope.getValueFromChild=function(){
  var childScope=angular.element('#child').scope();
  console.log(childScope.varChild);
  }
});

app.controller('ChildCtrl',function($scope){
 $scope.varChild="Hello Child";
  $scope.getValueFromParent=function(){
  var parentScope=angular.element('#parent').scope();
  console.log(parentScope.varParent);
  }
}); 

In above code controllers are showing their own value on Html and when you will click on text you will get values in console accordingly.If you click on parent controllers span, browser will console value of child and viceversa.

Solution 4 - Javascript

Here is a one-page example of two controllers sharing service data:

<!doctype html>
<html ng-app="project">
<head>
	<title>Angular: Service example</title>
	<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
	<script>
var projectModule = angular.module('project',[]);

projectModule.factory('theService', function() {  
	return {
		thing : {
			x : 100
		}
	};
});

function FirstCtrl($scope, theService) {
	$scope.thing = theService.thing;
	$scope.name = "First Controller";
}

function SecondCtrl($scope, theService) {	
	$scope.someThing = theService.thing; 
	$scope.name = "Second Controller!";
}
	</script>
</head>
<body>	
	<div ng-controller="FirstCtrl">
		<h2>{{name}}</h2>
		<input ng-model="thing.x"/>    		
	</div>

	<div ng-controller="SecondCtrl">
		<h2>{{name}}</h2>
		<input ng-model="someThing.x"/>     		
	</div>
</body>
</html>

Also here: https://gist.github.com/3595424

Solution 5 - Javascript

If you are looking to emit & broadcast events to share data or call functions across controllers, please look at this link: and check the answer by zbynour (answer with max votes). I am quoting his answer !!!

If scope of firstCtrl is parent of the secondCtrl scope, your code should work by replacing $emit by $broadcast in firstCtrl:

function firstCtrl($scope){
    $scope.$broadcast('someEvent', [1,2,3]);
}

function secondCtrl($scope){
    $scope.$on('someEvent', function(event, mass) {console.log(mass)});
}

In case there is no parent-child relation between your scopes you can inject $rootScope into the controller and broadcast the event to all child scopes (i.e. also secondCtrl).

function firstCtrl($rootScope){
    $rootScope.$broadcast('someEvent', [1,2,3]);
}

Finally, when you need to dispatch the event from child controller to scopes upwards you can use $scope.$emit. If scope of firstCtrl is parent of the secondCtrl scope:

function firstCtrl($scope){
    $scope.$on('someEvent', function(event, data) { console.log(data); });
}

function secondCtrl($scope){
    $scope.$emit('someEvent', [1,2,3]);
}

Solution 6 - Javascript

Two more fiddles: (Non service approach)

  1. For Parent- Child controller - Using $scope of parent controller to emit/broadcast events. http://jsfiddle.net/laan_sachin/jnj6y/

  2. Using $rootScope across non-related controllers. http://jsfiddle.net/VxafF/

Solution 7 - Javascript

Actually using emit and broadcast is inefficient because the event bubbles up and down the scope hierarchy which can easily degrade into performance bottlement for a complex application.

I would suggest using a service. Here is how I recently implemented it in one of my projects - https://gist.github.com/3384419.

Basic idea - register a pub-sub/event bus as a service. Then inject that event bus where ever you need to subscribe or publish events/topics.

Solution 8 - Javascript

I also know of this way.

angular.element($('#__userProfile')).scope().close();

But I don't use it too much, because I don't like to use jQuery selectors in angular code.

Solution 9 - Javascript

There is a method not dependent on services, $broadcast or $emit. It's not suitable in all cases, but if you have 2 related controllers that can be abstracted into directives, then you can use the require option in the directive definition. This is most likely how ngModel and ngForm communicate. You can use this to communicate between directive controllers that are either nested, or on the same element.

For a parent/child situation, the use would be as follows:

<div parent-directive>
  <div inner-directive></div>
</div>

And the main points to get it working: On the parent directive, with the methods to be called, you should define them on this (not on $scope):

controller: function($scope) {
  this.publicMethodOnParentDirective = function() {
    // Do something
  }
}

On the child directive definition, you can use the require option so the parent controller is passed to the link function (so you can then call functions on it from the scope of the child directive.

require: '^parentDirective',
template: '<span ng-click="onClick()">Click on this to call parent directive</span>',
link: function link(scope, iElement, iAttrs, parentController) {
  scope.onClick = function() {
    parentController.publicMethodOnParentDirective();
  }
}

The above can be seen at http://plnkr.co/edit/poeq460VmQER8Gl9w8Oz?p=preview

A sibling directive is used similarly, but both directives on the same element:

<div directive1 directive2>
</div>

Used by creating a method on directive1:

controller: function($scope) {
  this.publicMethod = function() {
    // Do something
  }
}

And in directive2 this can be called by using the require option which results in the siblingController being passed to the link function:

require: 'directive1',
template: '<span ng-click="onClick()">Click on this to call sibling directive1</span>',
link: function link(scope, iElement, iAttrs, siblingController) {
  scope.onClick = function() {
    siblingController.publicMethod();
  }
}

This can be seen at http://plnkr.co/edit/MUD2snf9zvadfnDXq85w?p=preview .

The uses of this?

  • Parent: Any case where child elements need to "register" themselves with a parent. Much like the relationship between ngModel and ngForm. These can add certain behaviour that can affects models. You might have something purely DOM based as well, where a parent element needs to manage the positions of certain children, say to manage or react to scrolling.

  • Sibling: allowing a directive to have its behaviour modified. ngModel is the classic case, to add parsers / validation to ngModel use on inputs.

Solution 10 - Javascript

I don't know if this is out of standards but if you have all of your controllers on the same file, then you can do something like this:

app = angular.module('dashboardBuzzAdmin', ['ngResource', 'ui.bootstrap']);

var indicatorsCtrl;
var perdiosCtrl;
var finesCtrl;

app.controller('IndicatorsCtrl', ['$scope', '$http', function ($scope, $http) {
  indicatorsCtrl = this;
  this.updateCharts = function () {
    finesCtrl.updateChart();
    periodsCtrl.updateChart();
  };
}]);

app.controller('periodsCtrl', ['$scope', '$http', function ($scope, $http) {
  periodsCtrl = this;
  this.updateChart = function() {...}
}]);

app.controller('FinesCtrl', ['$scope', '$http', function ($scope, $http) {
  finesCtrl = this;
  this.updateChart = function() {...}
}]);

As you can see indicatorsCtrl is calling the updateChart funcions of the other both controllers when calling updateCharts.

Solution 11 - Javascript

You can inject '$controller' service in your parent controller(MessageCtrl) and then instantiate/inject the child controller(DateCtrl) using:
$scope.childController = $controller('childController', { $scope: $scope.$new() });

Now you can access data from your child controller by calling its methods as it is a service.
Let me know if any issue.

Solution 12 - Javascript

Following is a publish-subscribe approach that is irrespective of Angular JS.

Search Param Controller

//Note: Multiple entities publish the same event
regionButtonClicked: function () 
{
        EM.fireEvent('onSearchParamSelectedEvent', 'region');
},

plantButtonClicked: function () 
{
        EM.fireEvent('onSearchParamSelectedEvent', 'plant');
},

Search Choices Controller

//Note: It subscribes for the 'onSearchParamSelectedEvent' published by the Search Param Controller
localSubscribe: function () {
        EM.on('onSearchParamSelectedEvent', this.loadChoicesView, this);

});


loadChoicesView: function (e) {

        //Get the entity name from eData attribute which was set in the event manager
        var entity = $(e.target).attr('eData');

        console.log(entity);

        currentSelectedEntity = entity;
        if (entity == 'region') {
            $('.getvalue').hide();
            this.loadRegionsView();
            this.collapseEntities();
        }
        else if (entity == 'plant') {
            $('.getvalue').hide();
            this.loadPlantsView();
            this.collapseEntities();
        }


});

Event Manager

myBase.EventManager = {

	eventArray:new Array(),


	on: function(event, handler, exchangeId) {
		var idArray;
		if (this.eventArray[event] == null) {
			idArray = new Array();
		} else { 
			idArray = this.eventArray[event];
		}
		idArray.push(exchangeId);
		this.eventArray[event] = idArray;

		//Binding using jQuery
        $(exchangeId).bind(event, handler);
	},

	un: function(event, handler, exchangeId) {

	    if (this.eventArray[event] != null) {
	        var idArray = this.eventArray[event];
	        idArray.pop(exchangeId);
	        this.eventArray[event] = idArray;

	        $(exchangeId).unbind(event, handler);
	    }
	},

	fireEvent: function(event, info) {
	    var ids = this.eventArray[event];

		for (idindex = 0; idindex < ids.length; idindex++) {
		    if (ids[idindex]) {

                //Add attribute eData
				$(ids[idindex]).attr('eData', info);
				$(ids[idindex]).trigger(event);
			}
		}
	}
};

Global

var EM = myBase.EventManager;

Solution 13 - Javascript

In angular 1.5 this can be accomplished by doing the following:

(function() {
  'use strict';

  angular
    .module('app')
    .component('parentComponent',{
      bindings: {},
      templateUrl: '/templates/products/product.html',
      controller: 'ProductCtrl as vm'
    });

  angular
    .module('app')
    .controller('ProductCtrl', ProductCtrl);

  function ProductCtrl() {
  	var vm = this;
    vm.openAccordion = false;

    // Capture stuff from each of the product forms
    vm.productForms = [{}];

    vm.addNewForm = function() {
      vm.productForms.push({});
    }
  }
  
}());

This is the parent component. In this I have created a function that pushes another object into my productForms array - note - this is just my example, this function can be anything really.

Now we can create another component that will make use of require:

(function() {
  'use strict';

  angular
    .module('app')
    .component('childComponent', {
      bindings: {},
      require: {
      	parent: '^parentComponent'
      },
      templateUrl: '/templates/products/product-form.html',
      controller: 'ProductFormCtrl as vm'
    });

  angular
    .module('app')
    .controller('ProductFormCtrl', ProductFormCtrl);

  function ProductFormCtrl() {
    var vm = this;

    // Initialization - make use of the parent controllers function
    vm.$onInit = function() {
      vm.addNewForm = vm.parent.addNewForm;
    };  
  }

}());

Here the child component is creating a reference to the parents component function addNewForm which can then be bound to the HTML and called like any other function.

Solution 14 - Javascript

You can use $controller service provided by AngularJS.

angular.module('app',[]).controller('DateCtrl', ['$scope', function($scope){
  $scope.currentDate = function(){
    return "The current date is: " + new Date().toString(); 
  }
}]);

angular.module('app').controller('MessageCtrl', ['$scope', function($scope){

  angular.extend(this, $controller('DateCtrl', {
      $scope: $scope
  }));

  $scope.messageWithDate = function(message){
    return "'"+ message + "', " + $scope.currentDate;
  }

  $scope.action2 = function(){
    console.log('Overridden in ChildCtrl action2');
  }

}]);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBanksySanView Question on Stackoverflow
Solution 1 - JavascriptVojtaView Answer on Stackoverflow
Solution 2 - JavascriptadardesignView Answer on Stackoverflow
Solution 3 - JavascriptShubham NigamView Answer on Stackoverflow
Solution 4 - JavascriptexclsrView Answer on Stackoverflow
Solution 5 - JavascriptSharpCoderView Answer on Stackoverflow
Solution 6 - JavascriptDarkKnightView Answer on Stackoverflow
Solution 7 - Javascriptnuman salatiView Answer on Stackoverflow
Solution 8 - JavascriptAndrey KorchakView Answer on Stackoverflow
Solution 9 - JavascriptMichal CharemzaView Answer on Stackoverflow
Solution 10 - JavascripttomascharadView Answer on Stackoverflow
Solution 11 - JavascriptSmrutiranjan SahuView Answer on Stackoverflow
Solution 12 - JavascriptLCJView Answer on Stackoverflow
Solution 13 - JavascriptKatana24View Answer on Stackoverflow
Solution 14 - JavascriptSagar KambleView Answer on Stackoverflow