Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

jquery - Preserving cursor position with angularjs

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-Zd]/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.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A way of doing this where

  • The input is only cleaned once
  • ngChange on the input is then only fired once

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-Zd]/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">

or if you would like an ngChange function:

<input type="text" clean-input ng-model="name" ng-change="onChange()">

This can be seen in-action at http://plnkr.co/edit/dAJ46XmmC49wqTgdp2qz?p=preview


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...