编译元素导致输入插入符位置移动到结束 [英] Compiling Element Causes Input Caret Position to Move to End

查看:190
本文介绍了编译元素导致输入插入符位置移动到结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指令一个问题。该指令的目的是为了方便地添加验证,而不必手动添加纳克级(除其他事项外),以要素,以获取错误状态展现出来。我只是单纯的想将我的元素上的验证指令,并有适当的类(和错误消息)时产生有一个错误状态。

至于验证的推移,它是工作很好,但它会导致奇数副作用。每当我编辑在上有验证指令的输入框中输入一个值,它移动插入符输入字段中的文本的结尾。它似乎是我编译元件(在这种情况下,包含该元素的父元素)的事实。

这里是一个jsbin 显示的问题。要重现,在字段中键入一个值,然后把插入符号在你刚刚输入值的中间,尝试输入其他字符。注意到它会移到字段的末端。请注意,如果你删除该值,因为预计将显示一个验证错误(字段是必需的)。

字段标签变成红色

下面是指令(从jsbin):

  angular.module(应用,[])
.directive('验证',函数($编译){
  返回{
    要求:'ngModel',
    限制:'A',
    编译:功能(compileElement,ATTRS){
      变种表格名称= compileElement [0] .form.name;
      compileElement.removeAttr('验证');
      compileElement.parent()ATTR('纳克级',表格名称+['+ attrs.name +'] $无效和放大器;&安培;+窗体名称+['+ attrs.name +' ?] $脏'错误':'');      返回功能(范围,元素){
        $编译(element.parent())(范围);
      }
    }
  };
});

这里是HTML:

 < HTML和GT;
  < HEAD>
  &所述; SCRIPT SRC =htt​​p://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js>&下; /脚本>
  < /头>
  <机身NG-应用=应用程序>
    <表格名称=subscribeForm>
    <标签>
      名字
      <输入类型=文本
             ID =名字
             NAME =名字
             NG-模式=userInfo.FirstName
             需要
             验证/>
    < /标签>
    < /表及GT;
  < /身体GT;
< / HTML>


解决方案

不知道,如果你想通了这一点,但我遇到了类似的问题。找到一个解决方案<一href=\"http://stackoverflow.com/questions/22940346/$p$pserving-cursor-position-with-angularjs\">$p$pserving光标angularjs 位置。为方便起见,以下是该指令代码片段,将解决这个问题。

  app.directive('cleanInput',函数(){
  返回{
    要求:'ngModel',
    链接:功能(范围,元素,ATTRS,ngModelController){
      变种埃尔=元素[0];      清洁功能(X){
        返回X&放大器;&安培; 。x.toUpperCase()代替(/ [^ A-Z \\ D] /克,'');
      }      ngModelController。$ parsers.push(功能(VAL){
        VAR清洗干净=(VAL);        //避免$ setViewValue&下的无限循环 - →; $解析器
        如果(清洗=== VAL)返回VAL;        VAR开始= el.selectionStart;
        VAR结束= el.selectionEnd + cleaned.length - val.length;        // element.val(清洁)不与表现
        //重复无效元素
        ngModelController $ setViewValue(清洗)。
        。ngModelController $渲染();        el.setSelectionRange(开始,结束);
        返回清洁;
      });
    }
  }
});

该指令有不同的目的,但这样根据您的要求进行修改。

I am having a problem with a directive. The purpose of the directive is to easily add validation without having to manually add ng-class (among other things) to elements in order to get the error state to show up. I just simply want to put a "validation" directive on my element and have the appropriate classes (and error messages) be generated when there is an error state.

As far as the validation goes, it is working great, but it causes an odd side effect. Whenever I am editing a value in an input box that has the validation directive on it, it moves the caret to the end of the text in the input field. It appears to be the fact that I'm compiling the element (in this case the parent element which contains this element).

Here is a jsbin showing the problem. To reproduce, type a value in the field, then put the caret in the middle of the value you just typed and try typing another character. Notice it moves you to the end of the field. Notice that if you delete the value, the field label turns red as expected to show a validation error (the field is required).

Here is the directive (from the jsbin):

angular.module('app', [])
.directive('validation', function($compile) {
  return {
    require: 'ngModel',
    restrict: 'A',
    compile: function(compileElement, attrs) {
      var formName = compileElement[0].form.name;
      compileElement.removeAttr('validation');
      compileElement.parent().attr('ng-class', formName + "['" + attrs.name + "'].$invalid && " + formName + "['" + attrs.name + "'].$dirty ? 'error' : ''");

      return function(scope, element) {
        $compile(element.parent())(scope);
      }
    }
  };
});

And here is the html:

<html>
  <head>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
  </head>
  <body ng-app="app">
    <form name="subscribeForm">
    <label>
      First Name
      <input type="text" 
             id="firstName" 
             name="firstName" 
             ng-model="userInfo.FirstName" 
             required 
             validation/>
    </label>
    </form>
  </body>
</html>

解决方案

not sure if you've figured this out but I encountered a similar problem. found a solution at Preserving cursor position with angularjs. for convenience, below is the directive snippet that would solve this issue.

app.directive('cleanInput', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModelController) {
      var el = element[0];

      function clean(x) {
        return x && x.toUpperCase().replace(/[^A-Z\d]/g, '');
      }

      ngModelController.$parsers.push(function(val) {
        var cleaned = clean(val);

        // Avoid infinite loop of $setViewValue <-> $parsers
        if (cleaned === val) return val;

        var start = el.selectionStart;
        var end = el.selectionEnd + cleaned.length - val.length;

        // element.val(cleaned) does not behave with
        // repeated invalid elements
        ngModelController.$setViewValue(cleaned);
        ngModelController.$render();

        el.setSelectionRange(start, end);
        return cleaned;
      });
    }
  }
});

the directive had a different purpose though so modify it according to your requirements.

这篇关于编译元素导致输入插入符位置移动到结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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