我需要在数字输入字段中显示 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=> 01:07))。ng-model 值($scope.timeHH & $scope.timeMM)在输入字段中不包含前导零。
我找到了这个问题的答案,但我无法让它工作。这是(答案)。
这是该指令的颂歌。它不会触发模糊或给出错误。任何人都可以看到结构或语法问题吗?
看法:
<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();
});
}
};
});