Skip to content

Commit 59edc50

Browse files
author
Nitish
committed
First Version
1 parent 9318689 commit 59edc50

File tree

2 files changed

+86
-2
lines changed

2 files changed

+86
-2
lines changed

README.md

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,66 @@
1-
Angularjs-Directive-Accept-Number-Only
1+
Angularjs Directive Accept Number Only
22
======================================
33

4-
A angularjs directive which allows only numbers with decimal to be typed into a text box .
4+
A angularjs directive which allows only numbers to be typed into a text box .
5+
6+
7+
## FEATURES
8+
--------
9+
10+
* Accepts only numbers.
11+
* Accepts negative number.
12+
* Accepts floating Number
13+
14+
15+
## DEMO
16+
--------
17+
18+
[Accept Number Only](http://demos.nitishkumarsingh.com/angular-directive-accept-number-only/).
19+
20+
21+
## HOW TO USE
22+
---------------
23+
24+
```
25+
just add "nks-only-number".
26+
<input type="text" nks-only-number ng-model="mynumber"/>
27+
```
28+
29+
#### Directive Code
30+
--------------------
31+
32+
```
33+
Add this directive in your application.
34+
35+
app.directive('nksOnlyNumber', function () {
36+
return {
37+
restrict: 'EA',
38+
require: 'ngModel',
39+
link: function (scope, element, attrs, ngModel) {
40+
scope.$watch(attrs.ngModel, function(newValue, oldValue) {
41+
var spiltArray = String(newValue).split("");
42+
if (spiltArray.length === 0) return;
43+
if (spiltArray.length === 1 && (spiltArray[0] == '-' || spiltArray[0] === '.' )) return;
44+
if (spiltArray.length === 2 && newValue === '-.') return;
45+
46+
/*Check it is number or not.*/
47+
if (isNaN(newValue)) {
48+
ngModel.$setViewValue(oldValue);
49+
ngModel.$render();
50+
}
51+
});
52+
}
53+
};
54+
});
55+
56+
```
57+
58+
#### Next Version will include:
59+
-----------------------------------
60+
61+
* Min-Max for number
62+
* Control over Decimal Number - Add only numbers not floating number
63+
* Control over Negative Number - Can't add negative number
64+
65+
66+

accept-number-only.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
2+
angular.module('mainApp', [])
3+
.directive('nksOnlyNumber', function () {
4+
return {
5+
restrict: 'EA',
6+
require: 'ngModel',
7+
link: function (scope, element, attrs, ngModel) {
8+
scope.$watch(attrs.ngModel, function(newValue, oldValue) {
9+
var spiltArray = String(newValue).split("");
10+
if (spiltArray.length === 0) return;
11+
if (spiltArray.length === 1 && (spiltArray[0] == '-' || spiltArray[0] === '.' )) return;
12+
if (spiltArray.length === 2 && newValue === '-.') return;
13+
14+
/*Check it is number or not.*/
15+
if (isNaN(newValue)) {
16+
ngModel.$setViewValue(oldValue);
17+
ngModel.$render();
18+
}
19+
});
20+
}
21+
};
22+
});

0 commit comments

Comments
 (0)