preserving光标angularjs位置 [英] Preserving cursor position with angularjs
问题描述
下面的代码片段做什么,我想一个输入
,也就是说,它会删除所有非字母数字字符,转换为大写,preserves光标位置。
The following snippet does what I want to an input
, i.e., it removes all non-alphanumerical characters, converts to uppercase, and preserves the cursor position.
element = $(element);
element.keyup(function() {
var x = element.val();
var y = x && x.toUpperCase().replace(/[^A-Z\d]/g, '');
if (x===y) return;
var start = this.selectionStart;
var end = this.selectionEnd + y.length - x.length;
element.val(y);
this.setSelectionRange(start, end);
});
我把这个片段在指令的链接
和它的作品....居多。
I placed this snippet in the link
of a directive and it works.... mostly.
问题是,角
模式的改变被应用的前看到值的。我试图谷歌如何使用 $适用
或 $消化
或什么在这里,但毫无效果。
The problem is that the angular
model sees the value before the change gets applied. I tried to Google for how to use $apply
or $digest
or whatever here, but nothing worked.
(事实上,我不知怎么了,但随后的含量,重新呈现和我失去了位置,我无法重现它,但它不够好,反正。)
(Actually, I somehow managed it, but then the content was re-rendered and I lost the position. I can't reproduce it, but it wasn't good enough, anyway.)
推荐答案
这样的一种方式,其中
- 输入只清洗一次
-
ngChange
输入,然后只触发一次
- The input is only cleaned once
ngChange
on the input is then only fired once
是使用 $解析器
数组的的 ngModelController 提供。它的设计作为一个地方影响模型值(经由它的返回值),但它也可以作为一个监听到的输入事件。
is to use the $parsers
array that the ngModelController provides. It's designed as a place to affect the model value (via its return value), but it also can be used as a listener to input events.
app.directive('cleanInput', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModelController) {
var el = element[0];
function clean(x) {
return x && x.toUpperCase().replace(/[^A-Z\d]/g, '');
}
ngModelController.$parsers.push(function(val) {
var cleaned = clean(val);
// Avoid infinite loop of $setViewValue <-> $parsers
if (cleaned === val) return val;
var start = el.selectionStart;
var end = el.selectionEnd + cleaned.length - val.length;
// element.val(cleaned) does not behave with
// repeated invalid elements
ngModelController.$setViewValue(cleaned);
ngModelController.$render();
el.setSelectionRange(start, end);
return cleaned;
});
}
}
});
不过,我不知道,如果 $解析器的这种用法
是一个黑客位的。该指令可以作为:
However, I'm not sure if this usage of $parsers
is a bit of a hack. The directive can be used as:
<input type="text" clean-input ng-model="name">
或者如果你想一个 ngChange
功能:
<input type="text" clean-input ng-model="name" ng-change="onChange()">
这可以行动在<一中可以看出href=\"http://plnkr.co/edit/dAJ46XmmC49wqTgdp2qz?p=$p$pview\">http://plnkr.co/edit/dAJ46XmmC49wqTgdp2qz?p=$p$pview
这篇关于preserving光标angularjs位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!