|
1 | | -Angularjs-Directive-Accept-Number-Only |
| 1 | +Angularjs Directive Accept Number Only |
2 | 2 | ====================================== |
3 | 3 |
|
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 | + |
0 commit comments