ngModel.$parsers 在 ng-model 值的末尾插入空格 [英] ngModel.$parsers ingore whitespace at the end of ng-model value

查看:25
本文介绍了ngModel.$parsers 在 ng-model 值的末尾插入空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的指令:

 .directive('noWhitespace', ['$parse', function($parse) {返回 {限制:'A',要求:'ngModel',链接:函数(范围、元素、属性、ngModel){/*scope.$watch(attrs.ngModel, function(value) {var getter = $parse(value);更新(获取者(范围));});*/功能更新(视图值){console.log(JSON.stringify(viewValue));如果 (viewValue.match(/\s/)) {ngModel.$setValidity('whitespace', false);返回未定义;} 别的 {ngModel.$setValidity('whitespace', true);返回视图值;}}ngModel.$parsers.unshift(更新);}};}])

当我像这样使用它时:

<input ng-model="myValue" no-whitespace/><div ng-show="something.myValue.$error.whitespace">错误

</表单>

然后我输入了一些东西,然后在末尾有几个空格 update 不会被调用,直到我在这些空格之后输入字符,然后我得到了我有空格的错误.(当我在开头放置空格或仅放置空格时也会发生同样的情况).为什么会这样,如何解决?正如您在评论中看到的,我尝试使用 $watch+$parse 但得到错误 Cannot read property 'match' of undefined.

解决方案

在你的模板中试试这个:

<输入 ng-model="myValue" 无空格 ng-trim="false"/><div ng-show="something.myValue.$error.whitespace">错误

</表单>

这应该可以解决进入空白区域时 ng-model 不更新的问题.

Derp,该属性在输入元素中而不是在 div 中......

I have directive like this:

  .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);
      }
    };
  }])

and when I use it like this:

<form name="something" novalidate>
  <input ng-model="myValue" no-whitespace/>
  <div ng-show="something.myValue.$error.whitespace">
    Error
  </div>
</form>

and I type something and then few spaces at the end update is not called until I type character after those spaces and then I got error that I have whitespace. (the same happen when I put spaces at the begining or only spaces). Why is that, and how to fix it? As you see in comments I've try to use $watch+$parse but got error Cannot read property 'match' of undefined.

解决方案

Try this in your template:

<form name="something" novalidate>
  <input ng-model="myValue" no-whitespace ng-trim="false"/>
  <div ng-show="something.myValue.$error.whitespace">
    Error
  </div>
</form>

That should solve the issue of ng-model not updating when you enter empty space.

EDIT: Derp, the attribute goes in the input element not in the div ...

这篇关于ngModel.$parsers 在 ng-model 值的末尾插入空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆