![](/img/trans.png)
[英]ngModel.$setViewValue is not a function when trying to set model value
[英]ngModel.$parsers ingore whitespace at the end of ng-model value
我有這樣的指示:
.directive('noWhitespace', ['$parse', function($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
/*
scope.$watch(attrs.ngModel, function(value) {
var getter = $parse(value);
update(getter(scope));
});
*/
function update(viewValue) {
console.log(JSON.stringify(viewValue));
if (viewValue.match(/\s/)) {
ngModel.$setValidity('whitespace', false);
return undefined;
} else {
ngModel.$setValidity('whitespace', true);
return viewValue;
}
}
ngModel.$parsers.unshift(update);
}
};
}])
當我像這樣使用它時:
<form name="something" novalidate>
<input ng-model="myValue" no-whitespace/>
<div ng-show="something.myValue.$error.whitespace">
Error
</div>
</form>
然后我輸入一些東西,然后在最后update
幾個空格直到我在那些空格之后鍵入字符然后我得到錯誤,我有空格。 (當我在開頭或只有空格處放置空格時也是如此)。 為什么這樣,以及如何解決它? 正如你在評論中看到的那樣,我嘗試使用$watch+$parse
但是得到錯誤Cannot read property 'match' of undefined
。
在模板中嘗試此操作:
<form name="something" novalidate>
<input ng-model="myValue" no-whitespace ng-trim="false"/>
<div ng-show="something.myValue.$error.whitespace">
Error
</div>
</form>
這應該可以解決當您輸入空白空間時ng-model不更新的問題。
編輯:Derp,屬性進入輸入元素而不是div ...
這是角度模型解析器的預期行為,其思想是如果輸入的文本不正確(最后有空格),則ngModel
應返回undefined
。 當你考慮它時,如果根據你的驗證不正確,為什么還要為ngModel
保存一個值呢?
這是相關的一點:
if (viewValue.match(/\s/)) {
ngModel.$setValidity('whitespace', false);
return undefined;
}
您將有效性設置為false並返回undefined
。
即使僅通過僅返回viewValue
來驗證其值,也可以保持模型更新:
if (viewValue.match(/\s/))
ngModel.$setValidity('whitespace', false);
else
ngModel.$setValidity('whitespace', true);
// Return viewvalue regardless of whether it validates or not
return viewValue;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.