簡體   English   中英

角度:保留光標在被替換元素中的位置

[英]Angular: Preserving cursor position within replaced element

從高層次上講:我繼承了一些復雜的表單操作代碼,這些代碼有一個主要的可用性錯誤-編輯文本字段將每次更改后將光標移動到輸入文本的末尾。

我看着這個問題似乎很近,但是並沒有完全回答我的問題,因為有問題的元素正在使用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
        });
        }

    }; 
});

盡管我不止一次閱讀所有文檔,但我對整個角度編譯/鏈接生命周期絕對沒有很強的了解。 全面的流程圖會很好...

而是這樣做:

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

希望這可以幫助!

好吧,出於我的目的,事實證明我只需要在html中添加ng-model-options="{ updateOn: 'blur' }" 這樣可以防止模型更新和觸發替換,直到用戶完成編輯為止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM