0

I'm using ngModelController for formatting using input element. But I'm unable to set the caret position, if the user tries to enter any digit in the beginning or in the middle. As the caret alway jumps at the end.

What is the best place for calling set cursor?

ngModelController.$parsers.unshift(function (viewValue) {
                var plainNumber = viewValue.replace(/ /g, '');
                // $log.info(`viewValue = ${viewValue}`);
                console.log(`$modelValue = ${ngModelController.$modelValue} | $viewValue = ${ngModelController.$viewValue}`);
                console.log(`cursorPos = ${cursor.getCursorPos(elem[0])}`);
                var newVal = ""
                for (var i = 0; i < plainNumber.length; i++) {
                    if (i === 3 || i === 6) {
                        newVal += " ";
                    }
                    newVal += plainNumber[i];
                }

                cursor.setCursorPos(cursor.getCursorPos(elem[0]) + 1, elem[0]);

                // $log.info(`newVal = ${newVal}`);
                elem.val(newVal);
                return plainNumber;
            });
Cœur
  • 37,241
  • 25
  • 195
  • 267
Vivek Kumar
  • 4,822
  • 8
  • 51
  • 85

1 Answers1

0

similar question:

Preserving cursor position with angularjs

But I've added the below code, may be useful to other.

    ngModelController.$parsers.unshift(function (viewValue) {
        var plainNumber = viewValue.replace(/ /g, '');
        // $log.info(`viewValue = ${viewValue}`);
        console.log(`$modelValue = ${ngModelController.$modelValue} | $viewValue = ${ngModelController.$viewValue} | viewValue = ${viewValue} | cursorPos = ${cursor.getCursorPos(elem[0])} | oldVal = ${oldVal}`);
        var newVal = ""
        for (var i = 0; i < plainNumber.length; i++) {
            if (i === 3 || i === 6) {
                newVal += " ";
            }
            newVal += plainNumber[i];
        }

        if(newVal === viewValue) {
            return viewValue;
        }

        // $log.info(`newVal = ${newVal}`);
        var lastCursorPos = cursor.getCursorPos(elem[0]);
        elem.val(newVal);
        ngModelController.$setViewValue(newVal);
        ngModelController.$render();

        //cursor.setCursorPos(cursor.getCursorPos(elem[0]) + 1, elem[0]);
        elem[0].setSelectionRange(lastCursorPos + 1, lastCursorPos + 1);
        oldVal = newVal;

        return plainNumber;
    });
Community
  • 1
  • 1
Vivek Kumar
  • 4,822
  • 8
  • 51
  • 85