【问题标题】:Angular: Preserving cursor position within replaced elementAngular:在替换元素中保留光标位置
【发布时间】:2015-07-09 18:13:07
【问题描述】:

从高层次上讲:我继承了一些复杂的表单操作代码,这些代码存在一个主要的可用性错误——编辑文本字段后,每次更改后都会将光标移动到输入文本的末尾。

我查看了this question,这似乎很接近,但并没有完全回答我的问题,因为有问题的元素正在使用include-replace 模式。

我很难弄清楚如何结合这些方法。我不想更改输入的文本,只要确保光标不会跳来跳去。

据我了解,重新编译部分时会调用链接函数,每当底层模型发生更改时都会发生这种情况,每次用户编辑字段时都会发生这种情况。我可以通过将事件处理程序添加到我的 include-replace 的链接函数来捕获光标位置,但这无法访问将要被交换的元素。

myModule.directive('includeReplace', function () {
return {
    require: 'ngInclude',
    restrict: 'A', /* optional */
    link: function (scope, el, attrs) {
        el.replaceWith(el.children());

        el.on('change', function(event){
         var cursorPosition = event.target.selectionEnd;
         console.log(cursorPosition); // where I expect it
         el.selectionEnd; = cursorPosition; // but obviously this don't work
        });
        }

    }; 
});

尽管我已经不止一次地阅读了所有文档,但我绝对没有对整个 Angular 编译/链接生命周期有超强的把握。一个全面的流程图会很好......

【问题讨论】:

    标签: javascript jquery angularjs


    【解决方案1】:

    改为:

    el.on('change', function(event){
             var cursorPosition = event.target.selectionEnd;
             console.log(cursorPosition); // where I expect it
             el.selectionEnd; = cursorPosition; // but obviously this don't work
            });
            }
    

    怎么办:

    scope.$watch(function () {
      return el.val();
    }, function (value) {
      $timeout(function(){
        var cursorPosition = event.target.selectionEnd;
        console.log(cursorPosition); // where I expect it
        el.selectionEnd = cursorPosition;
      });
    });
    

    别忘了在你的指令中包含$timeout

    希望这会有所帮助!

    【讨论】:

    • 使用 scope.$watch 您正在“监视”元素值,每次更改时它都会触发下面的函数。
    • 我认为这会导致与另一种方式类似的问题,因为元素并没有真正“改变”,它被完全替换了。基本上,watch 函数在第一次创建后就不会触发,因为每次模型更改时,整个元素都会被替换。
    • 好的,我明白了。在那种情况下,我不明白这个问题,对此感到抱歉。无论如何,如果你看的是模型而不是值,会发生什么?也不行吗?
    • 我认为模型对光标位置一无所知
    【解决方案2】:

    好吧,就我的目的而言,我只需要将ng-model-options="{ updateOn: 'blur' }" 添加到 html 中。这可以防止模型在用户完成编辑之前更新和触发替换。

    【讨论】:

      猜你喜欢
      • 2014-07-18
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 2016-05-25
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      • 1970-01-01
      相关资源
      最近更新 更多