- AngularJS provides $directive() method to create custom directive.
- directive() method takes no of initialization argument to build the directive component.
- There is one important attribute names 'require' through which a directive can call the API method if any exist in the parent directive.
- In this Demo,"We will create 2 directive.In one of the directive a method is exposed and the other directive call this exposed method using require attribute".
- Below code contains two directive 'grid' and 'gridElement'.In 'grid' directive a method called getCounter() is exposed by using this reference inside the controller scope function.'gridElement' directive calls the grid directive controller using require attribute with the name of the parent directive.It has used ^ symbol to check the existence of the grid directive in the parent scope also.
<!DOCTYPE html> <html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<meta charset="utf-8">
<title>AngularJS custom directive with require attribute usage</title>
</head>
<body>
<grid count="4">
<grid-element></grid-element>
</grid>
</body>
<script>
var myApp = angular.module("myApp", []);
myApp.directive("grid", function() {
return {
restrict: "E",
scope: {
counter: '@count'
},
controller: function($scope) {
/*THis method is exposed as API*/
this.getCounter = function() {
return parseInt($scope.counter, 10);
};
}
};
});
myApp.directive('gridElement', function() {
return {
restrict: 'E',
//for multiple directive use require :['^directive1','^directive2']
require: '^grid',
template: '<div>value of counter attribute in grid directive is = {{elementSize}}</div>',
link: function(scope, element, attr, gridController) {
scope.elementSize = gridController.getCounter();
}
};
});
</script>
</html>
- Output of the above code is embedded in below JSBIN link.