ngModel。在NG-模型值的末尾$解析器则会忽略空白 [英] ngModel.$parsers ingore whitespace at the end of ng-model value

查看:116
本文介绍了ngModel。在NG-模型值的末尾$解析器则会忽略空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有指令是这样的:

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

推荐答案

试试这个在您的模板:

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

这应该解决的,当你进入空不更新NG-模式的问题。

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

编辑:DERP,属性变为输入元素没有在DIV ...

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

这篇关于ngModel。在NG-模型值的末尾$解析器则会忽略空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆