Introduction
Before reading this article there is only one prerequisite condition; you should know how to create a directive in AngularJs and why we need to create them.
Step 1
First of all you need to add AngularJs and jQuery to your page, just like here:
<head runat="server">
<title></title>
<script src="angular.min.js"></script>
<script src="jquery-1.11.1.min.js"></script>
</head>
You can either download them from my code that is available at the start of this article or you can download from their official websites.
(AngularJs file can be downloaded from here also).
Step 2
Now I am just adding a textbox where I need to allow only numbers using an AngularJs directive.
<body>
<form ng-app="app" id="form1" runat="server">
<div>
<h3> Demo to Allow Numbers Only </h3>
<hr />
Provide Your Mobile Number: <input type="text"
name="MobileNumber"
class="form-control"
allow-only-numbers />
<hr />
</div>
</form>
</body>
Step 3
Now we need to work on the Angular code, the main part of this article.
<script>
var app = angular.module('app', []);
app.directive('allowOnlyNumbers', function () {
return {
restrict: 'A',
link: function (scope, elm, attrs, ctrl) {
elm.on('keydown', function (event) {
if (event.which == 64 || event.which == 16) {
// to allow numbers
return false;
} else if (event.which >= 48 && event.which <= 57) {
// to allow numbers
return true;
} else if (event.which >= 96 && event.which <= 105) {
// to allow numpad number
return true;
} else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) {
// to allow backspace, enter, escape, arrows
return true;
} else {
event.preventDefault();
// to stop others
return false;
}
});
}
}
});
</script>
Here I first created a module named "app". The module creation is a necessary part if you want to use Angular. This module is added to the HTML page using the ng-app directive.



Hamid KhanPosted Nov 25, 2017, 12:24 PM
Great..................
SharadPosted Jul 22, 2015, 12:36 AM
Excellent..
Anubhav ChaudharyPosted Jul 13, 2015, 3:10 PM
ThanksSanthakumar Munuswamy
Santhakumar MunuswamyPosted Jul 13, 2015, 3:08 PM
Nice article! Thanks for sharing
Anubhav ChaudharyPosted Jul 13, 2015, 6:19 AM
Thanks Debendra Dash
Debendra DashPosted Jul 13, 2015, 1:33 AM
great.........