Directive is very powerful feature of AngularJS. It easily wired up with controller, html and do the DOM manipulations. Angular AngularJS provide very less details about directive. I thought I will cover some of the directive that I used in real projects.
Compile Function :
use for template DOM manipulation (i.e., manipulation of tElement = template element), hence manipulations that apply to all DOM clones of the template associated with the directive.
Example: disable all element in a DIV
- app.directive('disableContents', function () {
- return {
- compile: function (tElem, tAttrs) {
- var inputs = tElem.find('input');
- inputs.attr('ng-disabled',tAttrs['disableContents']);
- for(var i = 0; i < inputs.length; i++) {
- }
- }
- }
- });
Use for registering DOM listeners (i.e., $watch expressions on the instance scope) as well as instance DOM manipulation (i.e., manipulationof iElement = individual instance element).
Check Valid email on textbox blur
- app.directive('validEmail', ['$dependency', function ($dependency) {
- return {
- require: 'ngModel',
- link: function (scope, element, attrs, ngModel) {
- element.bind('blur', function (e) {
- if (!ngModel || !element.val()) return;
- var currentValue = element.val();
- var regex = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
- if (currentValue && !regex.test(currentValue)) {
- ngModel.$modelValue = '';
- element[0].value = '';
- alert(INVALID EMAIL);
- }
- });
- }
- }
- }]);
You can use directive in all scenario where you want to manipulate DOM elements.