Last active
December 16, 2016 13:56
-
-
Save olaferlandsen/c916fd0921f804713f26c1e37473615a to your computer and use it in GitHub Desktop.
ngNumber - Simple and powerful directive for allow only numbers on text input.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* How to use it? | |
* You only need set 'ng-number' attribute on you input like | |
Example: | |
* <input ng-model="myModel" ng-number> | |
* | |
* How to integrate? | |
* You need copy this code and paste after you module definition on you Angular app. | |
* Example: | |
* module('controllers', []) | |
* .directive('ngNumber', ...) | |
* .controller('myCtrl', ...) | |
* | |
* Support | |
* This directive can support next key: | |
* Numbers and only one dot: | |
* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and .(dot) | |
* Special: | |
* backspace(remove), left arrow, right arrow, tab | |
* Windows Combinations: | |
* ctrl+v ctrl+c ctrl+a ctrl+x | |
* OSX Combinations: | |
* cmd+v cmd+c cmd+a cmd+x | |
* Events: | |
* Copy, Paste, Cut, Input(keydown, keypress and keyup) | |
* | |
* Formats: | |
* Example: | |
* 0 (integer) | |
* 0.1 (float/double/decimal) | |
*/ | |
.directive('ngNumber', function () { | |
return function (scope, element) { | |
element.bind('keydown',function (event) { | |
var keys=[37,38,39,40,8,9,13,186,20,16,17,18,27,229,32,48,49,50,51,52,53,54,55,56,57,190]; | |
event.which == 190 && element.val().trim().indexOf('.') > -1 && event.preventDefault(); | |
event.which == 190 && element.val().trim().length == 0 && event.preventDefault(); | |
if (navigator.platform.indexOf('mac')) event.metaKey === true && [86,65,67,88].indexOf(event.which) == -1 && event.preventDefault() | |
else if (navigator.platform.indexOf('win')) event.ctrlKey === true && [86,65,67,88].indexOf(event.which) == -1 && event.preventDefault() | |
else keys.indexOf(event.which) < 0 && event.preventDefault(); | |
}); | |
element.bind('input', function(event){ | |
var value = element.val().trim().replace(/[^\d\.]+/g,'').replace( /^([^.]*\.)(.*)$/, function ( a, b, c ) { | |
return b + c.replace( /\./g, '' ); | |
}).replace(/^0([\d]+)$/, '$1') | |
element.val (value) | |
}) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment