可能已经回答了类似的问题(ng-pattern + ng-change),但所有回复都无法解决此问题。
我有两个用于创建表单输入的imbricated指令,一个用于控制名称,标签,验证器等的父指令,以及一个用于设置模式和输入类型特定内容的子指令。
但是,在设置模式时,当ng-pattern返回false时,模型上的值将设置为undefined。
指令:
<input-wrapper ng-model="vm.customer.phone" name="phone" label="Phone number">
<input-text type="tel"></input-text>
</input-wrapper>
生成的HTML:
<label for="phone">Phone number:</label>
<input type="text" name="phone"
ng-model="value"
ng-model-options="{ updateOn: \'blur\' }"
ng-change="onChange()"
ng-pattern="/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/">
JS:
angular.module('components', [])
.directive('inputWrapper', function() {
return {
restrict: 'E',
require: 'ngModel',
scope: true,
link: function (scope, element, attrs, ngModel) {
scope.name = attrs.name;
scope.label = attrs.label;
scope.onChange = function () {
ngModel.$setViewValue(scope.value);
};
ngModel.$render = function () {
scope.value = ngModel.$modelValue;
};
}
}
})
.directive('inputText', function() {
return {
restrict: 'E',
template: '<label for="{{name}}">{{label}}:</label><input type="text" name="{{name}}" ng-model="value" ng-model-options="{ updateOn: \'blur\' }" ng-change="onChange()" ng-pattern="pattern">',
link: function (scope, element, attrs) {
if (attrs.type === 'tel') {
scope.pattern = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/;
}
}
}
});
angular.module('app',['components'])
.controller('ctrl',function($scope){
var vm = this;
vm.customer = {
phone: '010203040506'
};
});
我做错了什么?
用例的Codepen:https://codepen.io/Yosky/pen/yVrmvw
答案 0 :(得分:5)
默认为角度,如果验证器失败,未定义的值分配给ng-model,您可以更改此设置,如下所示:
<div ng-model-options="{ allowInvalid: true}">
答案 1 :(得分:1)
我有一些要求,这意味着当验证无效时,我真的不希望ng-model写入未定义的作用域,并且我也不希望该无效值,所以allowInvalid并没有帮助。相反,我只是想ng-model不写任何东西,但是我找不到任何选择。
因此,除了对ng-model控制器进行了一些猴子修补之外,我看不到任何前进的方向。
因此,我首先在正在构建的require: { model: 'ngModel' }
组件中需要ngModel,然后在$ onInit钩子中执行此操作:
const writeModelToScope = this.model.$$writeModelToScope;
const _this = this;
this.model.$$writeModelToScope = function() {
const allowInvalid = _this.model.$options.getOption('allowInvalid');
if (!allowInvalid && _this.model.$invalid) {
return;
}
writeModelToScope.bind(this)();
};
当值无效且组件具有焦点时,我也不想采用新的模型值,所以我这样做了:
const setModelValue = this.model.$$setModelValue;
this.model.$$setModelValue = function(modelValue) {
_this.lastModelValue = modelValue;
if (_this.model.$invalid) {
return;
}
if (_this.hasFocus) {
return;
}
setModelValue.bind(this)(modelValue);
};
element.on('focus', () => {
this.hasFocus = true;
});
element.on('blur', (event) => {
this.hasFocus = false;
const allowInvalid = this.model.$options.getOption('allowInvalid');
if (!allowInvalid && this.model.$invalid) {
this.value = this.lastModelValue;
}
event.preventDefault();
});
随意判断我,只知道我已经很脏。