我试图通过同时使用 ng-pattern 和 ng-model 解析来真正喜欢角度输入。我放入 ng-pattern 的正则表达式在 regex101.com 上运行良好,甚至将其登录到我的应用程序中也运行良好。然而,当在 ng-pattern 中使用它时,它说我的输入是无效的,尽管它不应该是。我想知道 ng-pattern 什么时候做它的事情与 ngModel.$parsers/ngModel.$formatters 什么时候做他们的事情有关,因为我可以看到它导致它失败。这是一些代码:
这是 ngModel 解析指令:
UI.directive('formatSeconds', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
var padZero = function (num, size) {
return ('00' + num).substr(-size);
};
var formatSeconds = function (seconds) {
var min = Math.floor(seconds / 60);
var sec = Math.floor(seconds % 60);
var ms = Math.round(((seconds % 60) - sec) * 1000);
return min + ':' + padZero(sec, 2) + ':' + padZero(ms, 3);
};
var parseTime = function (time) {
time = time.split(':');
var min = parseInt(time[0] || 0);
var sec = parseInt(time[1] || 0);
var ms = parseInt(time[2] || 0);
return min * 60 + sec + (ms / 1000);
};
ngModel.$parsers.push(parseTime);
ngModel.$formatters.push(formatSeconds);
}
};
});
这是我的控制器中的正则表达式:
$scope.timeRegex = /^([0-9]+)?\:([0-5][0-9])\:?([0-9]{3})?$/;
这是我观点的相关部分:
<tbody ng-form name="syncForm">
<tr class="timing-entry" ng-repeat="entry in scenario.syncManifest">
<td>
<input type="text" ng-attr-name="{{'time' + $index}}" required ng-model="entry.time" format-seconds ng-pattern="timeRegex" />
</td>
</tr>
</tbody>
时间以entry
秒为单位,因此格式化程序将其置于 0:00:000 格式。然后我希望 ng-pattern 会启动并说是!有效的!但我想知道它是否在解析之前 time 属性仍为 0.000 格式时正在运行。