简体   繁体   中英

Angular: Preserving cursor position within replaced element

From a high level: I have inherited some complex form manipulation code that has a major usability bug--editing a text field moves the cursor to the end of the entered text after each change.

I looked at this question which seems close, but not quite answering my question because the elements in question are using the include-replace pattern.

I'm having a hard time figuring out how to combine these approaches. I don't want to change the entered text, just make sure the cursor doesn't hop around.

As I understand it, the link function gets called when the partial is recompiled, which is happening whenever a change to the underlying model occurs, which happens every time the user edits the field at all. I can capture the cursor location by adding an event handler to the link function of my include-replace, but this doesn't have access to the element that is going to be swapped in.

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
        });
        }

    }; 
});

I definitely don't have a super-strong grasp of the whole angular compile/link lifecycle, though I have read all the docs more than once. A comprehensive flow-chart would be nice...

Instead doing:

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
        });
        }

What about doing:

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;
  });
});

Don't forget to include $timeout in your directive.

Hope this helps!

Well, for my purposes, it turns out I simply needed to add the ng-model-options="{ updateOn: 'blur' }" to the html. This prevents the model from updating and triggering the replace until the user is finished editing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM