Introduction
Directive in AngularJS is very powerful concept. Directives allow the developers to design any kind of controls or components in AngularJS, which can be used in HTML as an attribute, element, etc. That provides us great flexibility.
I will explain here how to create a custom directive that allows only numbers in a text box. Then, the text box will not accept any string or even special characters.
Given below is the program defining the directive.
- var app = angular.module("myModule");
- app.directive("numbersOnly", function () {
- return {
- require: 'ngModel',
- link: function (scope, element, attr, ngModelCtrl) {
- function fromUser(text) {
- if (text) {
- var transformedInput = text.replace(/[^0-9]/g, '');
- if (transformedInput !== text) {
- ngModelCtrl.$setViewValue(transformedInput);
- ngModelCtrl.$render();
- }
- return transformedInput;
- }
- return undefined;
- }
- ngModelCtrl.$parsers.push(fromUser);
- }
- };
- });
The require:'ngModel' allows developer to inject the model attached to the element or its parent element on which the directive is bound to.
Its basically an easiest way to pass ngModel into the link/compile function instead passing it using a scope option. Once you have access to ngModel, you can change its value using $setViewValue, make it dirty/clean using $formatters, apply watchers, etc.
Load this directive into index.html file and use it like the below code in your text box.
- <input type="text"
- class="textFields" placeholder="Amount" ng-model="contactUsController.amount"
- numbers-only />
AngularJS directive is a very powerful feature. It provides great flexibility in the designing of any control or component, which provides modularization and re-usability.
Satish Kumar VadlavalliPosted Oct 24, 2016, 12:08 AM
Just check for whether this works for decimal numbers and negitive numbers
SubashPosted Oct 23, 2016, 9:22 PM
Nice share frirnd
Former memberPosted Oct 21, 2016, 4:02 AM
The explanation quality of code is very bad. you think u will paste the code and other will understand the meaning of every line. first try to learn the art of how to explain the code. it is very easy to pick and paste code from internet and post here.
Sreekanth ReddyPosted Oct 21, 2016, 2:28 AM
What is "numbers-only" in input tag ?