How to share data between directives in AngularJs

Sometimes you have to share data between controllers, to do that you can create a controller in parent directive and share that controller with child directive, let's see how you can achieve that in the following example.

What we are going to build

We are going to create to directives, one will be the parent of other, and we will share data from parent directive to child directive.

Html markup:

<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
	<meta charset="UTF-8">
	<title>Simple Directive Example</title>
	<script type="text/javascript" src="js/bower_components/angular/angular.min.js"></script>
</head>
<body>
	<parent>
		<child></child>
	</parent>

<script src="script.js"></script>
</body>
</html>

AngularJs ( script.js ):

(function() {
			var app = angular.module('app', [], function() {});

			app.directive('parent', function() {
				return {
					restrict : 'E',
					controller : function() {
						this.name = 'satish';

						this.setName = function(name) {
							this.name = name;
						}

						this.displayName = function() {
							console.log(this.name);
						}
					}
				}
			});


			app.directive('child', function() {
				return {
					restrict : 'E',
					require : '^parent',
					link : function(scope, element, attr, parentCtrl) {
						parentCtrl.setName('ashish');
						parentCtrl.displayName();
					}
				}
			});

	})();

As you can see in the child directive we can pass parent directive's controller in link function as fourth parameter, and manipulate it however we want, to do that you have to specify parent directive name  with caret as prefix in require property of child directive. 

Note: If you have hierarchy of directives which goes more than one level, you can pass directives in the require property as an array, for more information, head over to AngularJs documentation for directives.

That's it guys, now you can share data between directives, if you liked this article, please share this article, or if you have something to say please tell us in comment section or head to our forum to ask questions related to this tutorial.

Something to say? Tell us in comment section.