gpt4 book ai didi

javascript - ngModel.$parsers 忽略 ng-model 值末尾的空格

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:24:28 27 4
gpt4 key购买 nike

我有这样的指令:

  .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 ...

关于javascript - ngModel.$parsers 忽略 ng-model 值末尾的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24060325/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com