数字输入中缺少前导零

时间:2015-05-18 12:26:25

标签: javascript html angularjs input ng-pattern

我需要在数字输入字段中显示00-09之间整数的前导零。我正在使用angularJS。

输入字段的视图/模板(对不起html中的样式):

<script type="text/ng-template" id="form_field_time">
  <h3 style="color:coral ;">{{field.displayName}}</h3>
  <div ng-controller="timeAdjustCtrl">
      <input style="float:left; width:auto; margin-right:5px;" type="number" min='0' max='23' placeholder="HH" ng-model="timeHH" ng-change="adjustTimeHhMm(timeHH, timeMM, field)" ng-init="initTimeValues(field)"  />
      <p style="float:left; line-height:50px;font-size:1em;">:</p>
      <input style="float:left;width:auto; margin-left:5px;" type="number" min='0' max='59' step="1" placeholder="MM" ng-model="timeMM" ng-change="adjustTimeHhMm(timeHH, timeMM, field)" ng-init="initTimeValues(field)" />
      <p style="float:left; line-height:50px;font-size:1em;"> {{field.theValues[0]}}</p>
  <br style="clear:both;" />
  </div>  
</script>

我的控制器:

  app.controller('timeAdjustCtrl', ['$scope', 
  function ($scope) {

    $scope.adjustTimeHhMm = function(hours, minutes, field) {
      console.log($scope.timeHH);
      var strHH = String(hours);
      var strMM = String(minutes);

      var path = "00";
      var newHH = path.substring(0, path.length - strHH.length) + strHH;
      var newMM = path.substring(0, path.length - strMM.length) + strMM;
      var newHhMm = String(newHH+':'+newMM);
      console.log(newHH + ':' + newMM);
      field.theValues[0] = newHhMm; 
      console.log($scope.timeHH);
    }

    $scope.initTimeValues = function(field){
      if (field.theValues[0] != 'undefined'){
        $scope.timeHH = parseInt(field.theValues[0].substring(0,2));
        $scope.timeMM = parseInt(field.theValues[0].substring(3,5));
      }
    }
  }
]);

此输入字段或两个输入字段的集合设置时间值(小时和分钟),其存储为单个值(保持所需格式(HH:MM = ex =&gt; 01:07))。 ng-model值($ scope.timeHH&amp; $ scope.timeMM)不保留输入字段中的前导零。

enter image description here

我找到了这个问题的答案,但我无法让它发挥作用。这是(Answer)。

这是该指令的颂歌。它不会触发模糊也不会出错。任何人都可以看到结构或语法问题吗?

查看:

<script type="text/ng-template" id="form_field_time">
  <h3 style="color:coral ;">{{field.displayName}}</h3>
  <div ng-controller="timeAdjustCtrl">
      <input my-decimal style="float:left; width:auto; margin-right:5px;" type="number" min='0' max='23' placeholder="HH" ng-model="timeHH" ng-change="adjustTimeHhMm(timeHH, timeMM, field)" ng-init="initTimeValues(field)"  />
      <p style="float:left; line-height:50px;font-size:1em;">:</p>
      <input my-decimal style="float:left;width:auto; margin-left:5px;" type="number" min='0' max='59' step="1" placeholder="MM" ng-model="timeMM" ng-change="adjustTimeHhMm(timeHH, timeMM, field)" ng-init="initTimeValues(field)" />
      <p style="float:left; line-height:50px;font-size:1em;"> {{field.theValues[0]}}</p>
  <br style="clear:both;" />
  </div>  
</script>

指令(捕获输入字段上的模糊事件并避免前导零修剪)(放在我的控制器下面,用于输入字段(不在内部)):

 app.directive('myDecimals', function() {

    return {
      require: 'ngModel',
      link: function(scope, elm, attrs, ctrl) {

        elm.blur(function() {
            var val = ctrl.$viewValue;
            ctrl.$setViewValue(val * 1);
            ctrl.$render();
        });
      }
    };
  });

2 个答案:

答案 0 :(得分:0)

我遇到了类似的问题,其中从我的“文本”输入中修剪了前导零。当我调用ngModel.$setViewValue("123.8900")时,输入中显示的文本为“123.89”(模型正确设置为零)。

要在仍然正确设置模型的同时解决此问题,我同时调用:

var value = "123.8900";
ngModel.$setViewValue(value); //updates model but trims zeros in the view
inputEl[0].value = value; //prevents trimming of trailing zero but this alone wont update the model

答案 1 :(得分:-1)

我不喜欢这个解决方案 - 这种方法有一种烦人的闪烁,我对setTimeout调用特别不满意 - 但它似乎有用,并且避免了烦人的“那不是数字”错误Angular抛出。

angular.module('application', [])
    .directive('zeroPadded', function(){
        return{
            // limit to classes and attributes only
            // to use with CSS class, include "zeroPadded" in the class attribute
            // to use with attributes, add "zero-padded" to the input tag
            restrict: 'AC',
            link : function(scope, element){
                function padZeroesElement(ele){
                    if(ele.value < 10){
                        ele.value = "0" + ele.value;
                    }
                };

                function padZeroes(event){
                    padZeroesElement(event.target);
                };

                element.on('change', padZeroes);

                // hacky but not sure how else to ensure it's zero-padded   from the start
                setTimeout(function(){
                    for(var i = 0; i < element.length; i++){
                        padZeroesElement(element[i]);
                    }
                }, 1000);
            }
        };
    });

然后您的实际输入看起来像这样:

<input type="number" id="minute" ng-model="minute" min="0" max="59" step="1" zero-padded />