Angular : how to restrict input type number to allow only even number with min and max limit as well as steps to increase

标签 angularjs html angularjs-directive

我正在处理一个要求,我只想允许偶数到文本框或数字框(输入类型数字)。最小和最大限制从 4 到 14,如果我们有数字框,它应该只增加 2。

我尝试使用具有 min max 和 step 属性的 HTML 输入类型编号,它工作正常,但我们可以使用任何数字编辑文本框以限制我尝试使用指令,但它不适合我。如果有人能帮我解决这个问题,我会很高兴。

HTML :

<body ng-controller="ctrl">

new : <number-only-input step="2" min="4" max="14" input-value="wks.number" input-name="wks.name" >

</body>

脚本:

var app = angular.module('app', []);
app.controller('ctrl', function($scope){
    $scope.name = 'Samir Shah';
    $scope.price = -10;
    $scope.wks =  {number: '', name: 'testing'};
});

app.directive('numberOnlyInput', function () {
    return {
        restrict: 'EA',
        template: '<input type="text" name="{{inputName}}" ng-model="inputValue" />',
        scope: {
            inputValue: '=',
            inputName: '=',
            min: '@',
            max: '@',
            step: '@'
        },
        link: function (scope) {
            scope.$watch('inputValue', function(newValue,oldValue) {
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    scope.inputValue = oldValue;
                    return;
                }
                if(!isNaN(newValue)){
                        if(newValue < parseInt(scope.min) || newValue > parseInt(scope.max)){
                            scope.inputValue = oldValue;
                            return;
                        }
                }
            });
        }
    };
});

最佳答案

<form name="testForm">
<div ng-controller="MyCtrl">
    <input type="text" name="testInput" ng-model="number" ng-min="2" ng-max="14" required="required" numbers-only="numbers-only" />
    <div ng-show="testForm.testInput.$error.nonnumeric" style="color: red;">
        Numeric input only.
    </div>
    <div ng-show="testForm.testInput.$error.belowminimum" style="color: red;">
        Number is too small.
    </div>
    <div ng-show="testForm.testInput.$error.abovemaximum" style="color: red;">
        Number is too big.
    </div>
    <div ng-show="testForm.testInput.$error.odd" style="color: red;">
        Numeric is odd.
    </div>
</div>
</form>

angular.module('myApp', []).directive('numbersOnly', function () {
return {
    require: 'ngModel',
    link: function (scope, element, attrs, modelCtrl) {
        element.bind('blur', function () {
            if (parseInt(element.val(), 10) < attrs.ngMin) {
                modelCtrl.$setValidity('belowminimum', false);
                scope.$apply(function () {
                    element.val('');
                });
            }
        });
        modelCtrl.$parsers.push(function (inputValue) {
            // this next if is necessary for when using ng-required on your input. 
            // In such cases, when a letter is typed first, this parser will be called
            // again, and the 2nd time, the value will be undefined
            if (inputValue == undefined) return ''
            var transformedInput = inputValue.replace(/[^0-9]/g, '');
            if (transformedInput != inputValue || (parseInt(transformedInput, 10) < parseInt(attrs.ngMin, 10) && transformedInput !== '1') || parseInt(transformedInput, 10) > parseInt(attrs.ngMax, 10) || (transformedInput % 2 !== 0 && transformedInput !== '1')) {
                if (transformedInput != inputValue) {
                    modelCtrl.$setValidity('nonnumeric', false);
                } else {
                    modelCtrl.$setValidity('nonnumeric', true);
                }
                if (parseInt(transformedInput, 10) < parseInt(attrs.ngMin, 10) && transformedInput !== '1') {
                    modelCtrl.$setValidity('belowminimum', false);
                } else {
                    modelCtrl.$setValidity('belowminimum', true);
                }
                if (parseInt(transformedInput, 10) > parseInt(attrs.ngMax, 10)) {
                    modelCtrl.$setValidity('abovemaximum', false);
                } else {
                    modelCtrl.$setValidity('abovemaximum', true);
                }
                if (transformedInput % 2 !== 0 && transformedInput !== '1') {
                    modelCtrl.$setValidity('odd', false);
                } else {
                    modelCtrl.$setValidity('odd', true);
                }
                transformedInput = '';
                modelCtrl.$setViewValue(transformedInput);
                modelCtrl.$render();
                return transformedInput;
            }
            modelCtrl.$setValidity('nonnumeric', true);
            modelCtrl.$setValidity('belowminimum', true);
            modelCtrl.$setValidity('abovemaximum', true);
            modelCtrl.$setValidity('odd', true);
            return transformedInput;
        });
    }
};
});

活跃的 fiddle http://jsfiddle.net/tuckerjt07/1Ldmkmog/

关于 Angular : how to restrict input type number to allow only even number with min and max limit as well as steps to increase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31000193/

相关文章:

javascript - Angular JS 未捕获错误 : [$injector:modulerr] simple code

javascript - ExpressionEngine Safecracker guest 感谢电子邮件

javascript - 比较 innerHTML 和 jQuery

javascript - 如何使 Bootstrap 模式背景获得模糊效果

angularjs - Angular 谷歌地图 : could not find a valid center property?

angularjs - 每次激活 angularjs ui-router 命名 View 时如何运行 Controller ?

javascript - 如果使用 AngularJS 需要相应的表单元素,则用星号标记标签

angularjs - 如何使用 Websockets 更新 REST API 请求状态

angularjs - Angular - 错误 : $rootScope:infdig when setting a directive attribute using a controller variable

javascript - 如何执行注销触发器并进行 ngIf 身份验证检查 - Angular 4 和 Ionic 3