In this blog, we will see
What are Directives in AngularJS?
- Actually, they're markers on DOM Elements.
- With the help of Directives, we can extend HTML with the new attributes.
There are already lots of predefined Directives but apart from that, we can also create our own Directive.
Let us see how to create our own Directive.
Example. Directive for taking the numbers only as an input.
We will learn how to prevent the user from typing anything in the HTML textbox apart from numbers only.
In order to do this,
We need to perform the steps given below.
Step 1
First of all, add Directive given below in your controller.js. Directive is with the name validNumber.
The code snippet is given below for doing it.
- //Adding numeric values.
- angular.module("Sandip-MyModule").directive('validNumber', function ()
- {
- return {
- require: '?ngModel',
- link: function (scope, element, attrs, ngModelControl)
- {
- if (!ngModelControl)
- {
- return;
- }
- ngModelControl.$parsers.push(function (val)
- {
- if (angular.isUndefined(val))
- {
- var val = '';
- }
- var clean = val.replace(/[^/0-9]/g, '');
- var nCheck = clean.split('-');
- var dCheck = clean.split('.');
- if (!angular.isUndefined(nCheck[1]))
- {
- nCheck[1] = nCheck[1].slice(0, nCheck[1].length);
- clean = nCheck[0] + '-' + nCheck[1];
- if (nCheck[0].length > 0)
- {
- clean = nCheck[0];
- }
- }
- if (!angular.isUndefined(dCheck[1]))
- {
- dCheck[1] = dCheck[1].slice(0, 2);
- clean = dCheck[0] + '.' + dCheck[1];
- }
- if (val !== clean)
- {
- ngModelControl.$setViewValue(clean);
- ngModelControl.$render();
- }
- return clean;
- });
- element.bind('keypress', function (event)
- {
- if (event.keyCode === 32)
- {
- event.preventDefault();
- }
- });
- }
- };
- });

Sandip G PatilPosted Feb 5, 2017, 11:32 AM
Welcome.........thanks for feedback.......and I am also going to add more topic related to own directive in Angular JS
Sibiraj ThattalamPosted Feb 4, 2017, 2:42 AM
Thank you for sharing