阻止文本字段中的第一个数字

ale*_*nst 5 html javascript angularjs

我有一个文本输入绑定到一个包含5位数字的变量.如何阻止第一个数字,以便只有其他4个可编辑?

目前我有这个: ng-model="my_var" ng-pattern="/^\d{5}$/"

请注意,该值是双向绑定的,这意味着我正在显示它,用户可以编辑/保存它.

art*_*iak 2

这是一个可行的解决方案(您可能需要根据您的特定需求对其进行一些调整):

app.directive("filterInput", function () {

    return {
        require: 'ngModel', // controller to ng-model needed
        restrict: 'A',

        link: function (scope, element, attrs, modelCtrl) {

            var unchanged = attrs.filterInput;
            var regex = /^\d{0,5}$/; // the RegExp (in more generic solution could be passed from outside)

            modelCtrl.$parsers.push(function (inputValue) { // adding new $parser

                 if(inputValue[0] != unchanged){ // if the first digit is different from what it should be set value as the first digit
                    modelCtrl.$setViewValue(unchanged);
                    modelCtrl.$render();
                    return unchanged;
                }

                if(inputValue.length > 5){ // trim the input if it is longer than five -- it is not generic at all
                    var rv = inputValue.substring(0,5);

                    modelCtrl.$setViewValue(rv);
                    modelCtrl.$render();

                    return rv;
                }



                var transformedInput = regex.exec(inputValue);

                if (transformedInput != null) { // check if pattern exists
                    transformedInput = transformedInput[0];
                }
                else {
                    transformedInput = unchanged; // if not set the value to the not changeable part
                }

                if (transformedInput != inputValue) { // re-render if value changed
                    modelCtrl.$setViewValue(transformedInput); 
                    modelCtrl.$render();
                }
                return transformedInput;
            });
        }
    }
}); 
Run Code Online (Sandbox Code Playgroud)

以及如何使用它:

<p>var: {{my_var}}</p>
<input type="text" ng-model="my_var" filter-input="1"/>
Run Code Online (Sandbox Code Playgroud)

PLNKR

顺便说一句:它将只允许传递数字:-)