使用 AngularJS 在输入中设置插入符号位置 [英] Set Caret position in Input with AngularJS

查看:41
本文介绍了使用 AngularJS 在输入中设置插入符号位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更改输入的插入符号位置,其中添加了给定数量的数字(示例).

I need to change the caret position of an input, where a given number of digits is added (Example).

app.controller('MainCtrl', function($scope, $element, $timeout, $filter) {
  //$scope.val = '12';
  $scope.$watch('val', function(newValue, oldValue) {
    if (!isNaN(newValue)) {
      if (newValue.length > 3) {
        //Set Caret Position  
      }
    }
  });
});

是否可以做这样的事情示例?

Is it possible to do something like this example?

我需要例如:

输入:1234.

所以插入符号的位置是 2.

so the caret position will be 2.

新数字:9

最终:12934

提前致谢.

推荐答案

我认为这样的事情在指令中看起来更好.例如:

I think that such kind of things look better in directives. For example:

app.directive('caret', function() {

    function setCaretPosition(elem, caretPos) {
        if (elem !== null) {
            if (elem.createTextRange) {
                var range = elem.createTextRange();
                range.move('character', caretPos);
                range.select();
            } else {
                if (elem.setSelectionRange) {
                    elem.focus();
                    elem.setSelectionRange(caretPos, caretPos);
                } else
                    elem.focus();
            }
        }
    }

    return {
        scope: {value: '=ngModel'},
        link: function(scope, element, attrs) {
            var caret = Number(attrs.caret);
            scope.$watch('value', function(newValue, oldValue) {
                if (newValue && newValue != oldValue && !isNaN(newValue) && newValue.length > (caret + 1)) {
                    setCaretPosition(element[0], caret);
                }
            });
        }
    };
});

用法:

<input ng-model='val' caret="2" />

我从 this 答案中使用了 setCaretPosition 函数进行跨浏览器光标定位.

I used setCaretPosition function for cross browser cursor positioning from this answer.

这篇关于使用 AngularJS 在输入中设置插入符号位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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