我有一个绑定到包含5位数字的变量的文本输入。如何阻止第一个数字,以便只有其他4个可编辑?
目前我有这个:ng-model="my_var" ng-pattern="/^\d{5}$/"
请注意,该值是双向绑定的,这意味着我正在显示它,用户可以编辑/保存它。
答案 0 :(得分:3)
您可以使用与ngModel一起使用的自定义指令。
它可以使用解析器/格式化程序来修改读取/打印的值。
在此处阅读更多相关信息:http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController($ formatters和$ parsers)
答案 1 :(得分: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;
});
}
}
});
以及如何使用它:
<p>var: {{my_var}}</p>
<input type="text" ng-model="my_var" filter-input="1"/>
顺便说一下:它只允许传递数字: - )
答案 2 :(得分:0)
也许不是最好的解决方案,但它有效:
<强> HTML 强>
<input ng-model="my_var" maxlength="5">
<强>控制器强>
$scope.my_var = '1';
$scope.$watch('my_var', function(){
if($scope.my_var.length != 1){
if($scope.my_var.length == 0){
$scope.my_var = '1';
}
}
});