[英]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.