TrinityTuts

Communication between two controllers in angularjs

Last updated on January 8th, 2020 at 10:01 pm

AngularJs is very good template engine, handles Document object model (DOM) more efficiently. In this post iam going to explain how to communicate with multiple controller in angularjs using angular factory. If you want to learn some basics of angularjs you follow this link. If you have good knowledge of Javascript and jQuery then angular is relay easy for you. This post is really very easy to understand.

 

Live Demo

In angular communication between pages is done with help of controller and data sharing between controller is done by three way

  1. Factory: Object is created inside the factory and return it .
  2. Service: With the service, you just have a standard function that uses the this keyword to define function.
  3. Provider: With the provider, there’s a $get you define and it can be used to get the object that returns the data.

Sample Code

In this sample i am to create a simple angular script which contain three controller and first controller have a value which is increased +1 and +2 by other two controller. Here is a code

<html>
	<head>
		<title>Demo - Communication between two controllers in angularjs</title>
		<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
	</head>
	
	<body ng-app="commDemo">
		<div ng-controller="output">
			{{value}}
		</div>
		<div ng-controller="increaseOne">
			<button ng-click="increaseValueOne();">Add 1</button>
		</div>
		<div ng-controller="increaseTwo">
			<button ng-click="increaseValueTwo();">Add 2</button>
		</div>
		
		<script>
		var app = angular.module("commDemo" , []);
		app.factory('service', function($rootScope) {
			var service = {};
			
			service.value = 0;
			
			service.prepForBroadcast = function(count) {
				this.value = count;
				this.broadcastItem();
			};
			
			service.getValue = function () {
				return service.value;
			};
  
			service.broadcastItem = function() {
				$rootScope.$broadcast('handleBroadcast');
			};
			
			return service;
			
		});
		
		app.controller("output" , function($scope, service){
			$scope.value = 1;
			$scope.$on('handleBroadcast', function() {
				$scope.value = service.value; 
			});
		});
		app.controller("increaseOne" , function($scope, service){
			$scope.increaseValueOne = function(){
				var value = parseInt(service.getValue());
				service.prepForBroadcast(value+1);
			}
		});
		app.controller("increaseTwo" , function($scope, service){
			$scope.increaseValueTwo = function(){
				var value = parseInt(service.getValue());
				service.prepForBroadcast(value+2);
			}
		});
		</script>
	</body>
</html>

to check this code working please click on demo link above. This is a simple example to learn how to communicate between different controller in angular js.