输入反向写入

时间:2016-12-27 16:14:28

标签: angularjs ecmascript-6

我需要实现一些带有一些限制的输入字段。 首先,它需要有默认的零和最大长度= 4   使用程序如下:

初始输入状态: 0000 开始输入(字符): 1 输入状态后: 0001 下面打字: 2 输入状态后: 0012

为了使用默认零,我使用Angualar Ui Mask ui-mask-placeholder

这是我的输入

<input type="text" ui-mask-placeholder="0000" ui-mask="9999" ng-model="$ctrl.storeId"  maxlength="4" required />

我需要的是使输入插入符以这种方式放置以反向写入在输入数字之前始终为零

我寻求解决方案的尝试是:

指示
<input type="text" ui-mask-placeholder="0000" ui-mask="9999" ng-model="$ctrl.storeId"  modify-input-with-zeros maxlength="4" required />


const modifyInputWithZerosFactory = () => {
  'ngInject'
   return {
    restrict: 'A',
      link: (scope, element, attrs) => {
       var maxValLength = parseInt(attrs.maxlength)
       var step = 0
       element[0].selectionStart = maxValLength - 1
       element.on('input', function() {
         step = step + 1
         element[0].selectionStart = maxValLength - step
       })
    }
  }
}

1 个答案:

答案 0 :(得分:3)

这适用于任何长度作为您的要求。只需在控制器

中给出最大长度值

<强> HTML

<!DOCTYPE html>
<html data-ng-app="app">

<head>
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body data-ng-controller="MyCtrl">

   <input type="text" ng-model="num" ng-keypress="makeInputReverse($event)" maxlength="{{maxLength}}"/>
</body>

</html>

<强>的script.js

var app = angular.module('app', []);
app.controller('MyCtrl', function($scope){

  $scope.num = "";
  $scope.maxLength = 4;

  for(var i=0; i<$scope.maxLength; i++){$scope.num = $scope.num+'0'}
  var noOfZeros = $scope.num;

  $scope.makeInputReverse = function(event){
    if($scope.num.length == $scope.maxLength && $scope.num[0] != '0'){
      event.preventDefault();
    } else if(event.keyCode < 48 || event.keyCode > 57){
          event.preventDefault();
    } else{
      if($scope.num.length <= $scope.maxLength || $scope.num == noOfZeros){
        if(!$scope.num) $scope.num = 0;
        $scope.num = (parseInt($scope.num) * 10) + parseInt(String.fromCharCode(event.which));
        $scope.num = noOfZeros + $scope.num;
        $scope.num = ($scope.num).slice($scope.num.length-$scope.maxLength, $scope.num.length);
      }
    }
  }

})

这里我们有工作的plunker https://plnkr.co/edit/Y2cJrUGYcygvM9i6wKx5

注意:

 <input type="text" ng-model="$ctrl.num" ng-keypress="$ctrl.makeInputReverse($event)" maxlength="4"/>

但是,如果你想使用类似$ctrl.num,你必须编写控制器As语法ng-controller="MyCtrl as $ctrl"并将所有出现的$scope.num更改为this.num和{{1转到控制器中的$scope.akeInputReverse