angularjs文本框必须具有最大长度数字

时间:2018-05-29 11:43:02

标签: angularjs

我有30个文本框第一个文本框必须有9个数字,第二个文本框必须有3个数字,我有这样的代码,在第一个文本框达到最大长度后它移动到下一个文本框。

我怎样才能做到这一点?

function numOnly() {
  var directive = {
      restrict: 'A',
      scope: {
          ngModel: '=ngModel'
      },
      link: link
  };
  return directive;

  function link(scope, element, attrs) {
    scope.$watch('ngModel', function (newVal, oldVal) {
        var arr = String(newVal).split('');
        if (arr.length === 0) return;
        if (arr.length === 1 && (arr[0] === '-' || arr[0] === '.')) return;
        if (isNaN(newVal)) {
            //scope.ngModel = oldVal;
            scope.ngModel = "";
        }
    });
}
<tr ng-repeat="cl in codelist" ng-if="$odd" >
    <td>{{$index+1}}</td>
    <td>
        <label ng-model="codelist[$index].CodeNumber">{{codelist[$index].CodeNumber}}</label>
    </td>
    <td ng-class="{ 'has-error' : codeForm.clHtnoA{{$index}}.$invalid && (codeForm.clHtnoA{{$index}}.$dirty || submitted) }">
        <input type="text" name="clHtnoA{{$index}}" ng-model="codelist[$index].HtnoA" num-only maxlength="9" ng-readonly="{{codelist[$index].Status}}" required class="form-control" />
        <span ng-show="codeForm.clHtnoA{{$index}}.$error.required && (codeForm.clHtnoA{{$index}}.$invalid.$dirty || submitted)" class="help-block">HallTicket is required.</span>
    </td>
    <td ng-class="{ 'has-error' : codeForm.clHtnoB{{$index}}.$invalid && (codeForm.clHtnoB{{$index}}.$dirty || submitted) }">
        <input type="text" name="clHtnoB{{$index}}" ng-model="codelist[$index].HtnoB" num-only maxlength="3" ng-change="findNameAB($index)" ng-readonly="{{codelist[$index].Status}}" required class="form-control" />
        <span ng-show="codeForm.clHtnoB{{$index}}.$error.required && (codeForm.clHtnoB{{$index}}.$invalid.$dirty || submitted)" class="help-block">3 no's only.</span>
    </td>
    <td>
        <span ng-model="codelist[$index].Sname">{{codelist[$index].Sname}}</span>
    </td>
</tr>

My form looks like this

2 个答案:

答案 0 :(得分:1)

指令是你的解决方案:

app.directive("range", [function() {
        return {
            restrict: "A",
            link: function(scope, elem, attrs) {
                var range = parseInt(attrs.limitTo);
                angular.element(elem).on("keypress", function(e) {
                    if (this.value.length == range) e.preventDefault();
                });
            }
        }
    }]);


<input type="text" ng-model="mybox1" range="9"/>

答案 1 :(得分:0)

使用ng-maxlength

<div ng-app="myApp" ng-controller="myCtrl">
<form>
        <input type="text" id="part1" ng-model="myObject.part1"  ng-maxlength = "9"/>
        <input type="text" id="part2" ng-model="myObject.part2"  ng-maxlength = "3" />
    </form>
</div>