This question already has answers here:
How to autocapitalize the first character in an input field in AngularJS?

(15 个回答)


6年前关闭。




我有一个输入框。

我需要自动大写这个框。

是否有任何可用的属性或我需要在 Controller 上编码

我还需要在 Angular 模型中应用这种效果

最佳答案

是的,我们对此有一个指令:)
原始代码(用 TypeScript 编写)在 GitHub 上 https://github.com/ST-Software/STAngular/blob/master/src/directives/SgUpperCase.ts

//修复了光标在最后跳转的问题

someModule.directive("sgUpperCase", [function () {
    function getCaretPosition(inputField) {
        // Initialize
        var position = 0;
        // IE Support
        if (document.selection) {
            inputField.focus();
            // To get cursor position, get empty selection range
            var emptySelection = document.selection.createRange();
            // Move selection start to 0 position
            emptySelection.moveStart('character', -inputField.value.length);
            // The caret position is selection length
            position = emptySelection.text.length;
        }
        else if (inputField.selectionStart || inputField.selectionStart == 0) {
            position = inputField.selectionStart;
        }
        return position;
    }
    function setCaretPosition(inputElement, position) {
        if (inputElement.createTextRange) {
            var range = inputElement.createTextRange();
            range.move('character', position);
            range.select();
        }
        else {
            if (inputElement.selectionStart) {
                inputElement.focus();
                inputElement.setSelectionRange(position, position);
            }
            else {
                inputElement.focus();
            }
        }
    }
    return {
        require: "^ngModel",
        restrict: "A",
        link: function (scope, elm, attrs, ctrl) {
            var toUpperCase = function (inputValue) {
                if (!inputValue)
                    return inputValue;
                var modified = inputValue.toUpperCase();
                if (modified !== inputValue) {
                    var position = getCaretPosition(elm[0]);
                    ctrl.$setViewValue(modified);
                    ctrl.$render();
                    setCaretPosition(elm[0], position);
                }
                return modified;
            };
            ctrl.$parsers.push(toUpperCase);
            toUpperCase(scope[attrs.ngModel]); //Transform initial value
        }
    };
}]);

关于javascript - 如何在angular js中自动大写输入字段?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30097083/

10-09 16:46