Angular : Numeric Directive

only allow numeric value

by Nishchit Dhanani

HTML

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.1.4/angular.js"></script>
<div ng-controller="MyCtrl">
    
    <br>
        <br>
            <br>
    This input allow only numeric value .<br>
    
    <input type="text" numeric />
    
</div>

JavaScript

angular.module('myApp',[])
.directive('numeric', function() {
        return function(scope, element, attrs) {

            $(element[0]).numericInput({ allowFloat: true });

        };
    })

function MyCtrl($scope,$window) {
  
  
}


<!--    jquery plugin : download from  https://github.com/joshuadeleon/NumericInput/blob/master/numericInput.js ---------- -->
    
    
    
    
    
    
    
    
    
    (function( $ ) {
        // Plugin defaults
        var defaults = {
                allowFloat: false,
                allowNegative: false
        };        
        
        // Plugin definition
        //        allowFloat: (boolean) Allows floating point (real) numbers. If set to false only integers will be allowed. Default: false.
        //        allowNegative: (boolean) Allows negative values. If set to false only positive number input will be allowed. Default: false.
         $.fn.numericInput = function( options ) { 
                var settings = $.extend( {}, defaults, options ); 
                var allowFloat = settings.allowFloat;
                var allowNegative = settings.allowNegative;
                
                this.keypress(function (event) {
                        var inputCode = event.which;
                        var currentValue = $(this).val();

                        if (inputCode > 0 && (inputCode < 48 || inputCode > 57))        // Checks the if the character code is not a digit
                        {
                                if (allowFloat == true && inputCode == 46)        // Conditions for a period (decimal point)
                                {
                                        //Disallows a period before a negative
                                        if (allowNegative == true && getCaret(this) == 0 && currentValue.charAt(0) == '-') 
                                                return false;

                                        //Disallows more than one decimal point.
                   ...