jcu*_*bic 3 javascript validation angularjs angularjs-directive
我有这样的指示:
.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);
}
};
}])
Run Code Online (Sandbox Code Playgroud)
当我像这样使用它时:
<form name="something" novalidate>
<input ng-model="myValue" no-whitespace/>
<div ng-show="something.myValue.$error.whitespace">
Error
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
然后我输入一些东西然后在最后输入几个空格,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>
Run Code Online (Sandbox Code Playgroud)
这应该可以解决当您输入空白空间时ng-model不更新的问题.
编辑:Derp,属性进入输入元素而不是div ...
归档时间: |
|
查看次数: |
1948 次 |
最近记录: |