angular directive ignore non-numeric input

前端 未结 4 753
北荒
北荒 2020-11-30 06:37

I have to write some code for IE8. I have an ng-repeat creating a table filled with:



        
相关标签:
4条回答
  • 2020-11-30 07:07

    First include this code in js file numericInput.js

    Directive : -

    .directive('numeric', function() {
        return function(scope, element, attrs) {
    
            $(element[0]).numericInput({ allowFloat: true });
    
        };
    })
    

    HTML : -

     <input type="text" numeric />
    

    DEMO Numeric Demo

    0 讨论(0)
  • 2020-11-30 07:08

    HTML:

    <input production-qty type="text" maxlength="3" ng-model="qty1">
    

    Directive:

    app.directive('productionQty', function() {
      return {
        require: 'ngModel',
        link: function (scope, element, attr, ngModelCtrl) {
          function fromUser(text) {
            var transformedInput = text.replace(/[^0-9]/g, '');
            console.log(transformedInput);
            if(transformedInput !== text) {
                ngModelCtrl.$setViewValue(transformedInput);
                ngModelCtrl.$render();
            }
            return transformedInput;  // or return Number(transformedInput)
          }
          ngModelCtrl.$parsers.push(fromUser);
        }
      }; 
    });
    

    Plunker

    See also filters on ng-model in an input. My answer above is modeled off pkozlowski.opensource's answer.

    I looked at ng-pattern, but it does not filter what is shown in the textbox. It sets $scope.qty1 to undefined, but the undesired characters are visible in the textbox.

    0 讨论(0)
  • 2020-11-30 07:19

    not directive but I use just:

    controller:

        $scope.blockNonNumber = function (val, field){
    
           $scope[field] = val.toString().replace(/[^0-9]/g, '');
    
        }
    

    html:

    <input type="text" ng-model="price" ng-change="blockNonNumber(price, 'price')" pattern="[0-99]">
    

    it's not directive but can be used in directive as wellside

    0 讨论(0)
  • 2020-11-30 07:22

    HTML:

    <input type="number" name="graduationYear" ng-model="gradYear" only-num>
    

    Directive:

    directive('onlyNum', function() {
        return function(scope, element, attrs) {
    
            var keyCode = [8, 9, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 110];
            element.bind("keydown", function(event) {
                //console.log($.inArray(event.which,keyCode));
                if ($.inArray(event.which, keyCode) === -1) {
                    scope.$apply(function() {
                        scope.$eval(attrs.onlyNum);
                        event.preventDefault();
                    });
                    event.preventDefault();
                }
    
            });
        };
    });
    
    0 讨论(0)
提交回复
热议问题