Angular 1.3.19 改变ng-pattern
了打破 ui-mask 的行为。
目前,ng-pattern 指令在 changelog 中$viewValue
验证而不是$modelValue
-Reference 。
Angular 团队提供了自定义指令来恢复以前的行为。这是解决此问题的好方法。
当您同时使用和时,您必须pattern-model
向字段添加属性。ui-mask
ng-pattern
<input type="text"
class="form-control input-sm"
placeholder="hh:mm:ss"
name="hhmmss"
ng-model="data.hhmmss"
ng-pattern="/^([0-2]|0[0-9]|1[0-9]|2[0-3]):?[0-5][0-9]:?[0-5][0-9]$/"
ui-mask="99:99:99"
pattern-model
/>
指令代码(将其添加到您的代码库中):
.directive('patternModel', function patternModelOverwriteDirective() {
return {
restrict: 'A',
require: '?ngModel',
priority: 1,
compile: function() {
var regexp, patternExp;
return {
pre: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.$observe('pattern', function(regex) {
/**
* The built-in directive will call our overwritten validator
* (see below). We just need to update the regex.
* The preLink fn guarantees our observer is called first.
*/
if (angular.isString(regex) && regex.length > 0) {
regex = new RegExp('^' + regex + '$');
}
if (regex && !regex.test) {
//The built-in validator will throw at this point
return;
}
regexp = regex || undefined;
});
},
post: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
regexp, patternExp = attr.ngPattern || attr.pattern;
//The postLink fn guarantees we overwrite the built-in pattern validator
ctrl.$validators.pattern = function(value) {
return ctrl.$isEmpty(value) ||
angular.isUndefined(regexp) ||
regexp.test(value);
};
}
};
}
};
});
ui-mask GitHub 中的问题 -参考。