[英]Angular.js - ngModel value is undefined when ng-pattern is set in directive
可能已經回答了類似的問題(ng-pattern + ng-change),但所有響應都無法解決此問題。
我有兩個用於創建表單輸入的混合指令,一個用於控制名稱,標簽,驗證器等的父指令,以及一個用於設置模式和輸入類型特定內容的子指令。
但是,在設置模式時,當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
如果驗證器失敗,默認情況下為angular,為ng-model分配了未定義的值,您可以按以下方式更改此設置:
<div ng-model-options="{ allowInvalid: true}">
我有一些要求,這意味着當驗證無效時,我真的不希望ng-model寫入未定義的作用域,並且我也不希望該無效值,所以allowInvalid並沒有幫助。 相反,我只是想ng-model不寫任何東西,但是我找不到任何選擇。
因此,除了對ng-model控制器進行了一些猴子修補之外,我看不到任何前進的方向。
因此,首先我在要構建的組件中需要ngModel require: { model: '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();
});
隨意判斷我,只知道我已經很臟。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.