javascriptruby-on-railsangularjsnumeric

angularjs: allows only numbers to be typed into a text box


In angularjs is there any functionality available that allows only numbers to be typed into a text box like


Solution

  • This functionality just what you need. http://docs.angularjs.org/api/ng.directive:input.number

    EDIT:

    You can wrap the jquery plugin into directive. I created an example here: http://jsfiddle.net/anazimok/jTJCF/

    HTML:

    <div ng-app="myApp">
        <div>
            <input type="text" min="0" max="99" number-mask="" ng-model="message">
                <button ng-click="handleClick()">Broadcast</button>
        </div>
    
    </div>
    

    CSS:

    .ng-invalid {
        border: 1px solid red;
    }
    

    JS:

    // declare a module
    var app = angular.module('myApp', []);
    
    app.directive('numberMask', function() {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                $(element).numeric();
            }
        }
    });