javascript - 如何在angular js中自动大写输入字段?

标签 javascript jquery html angularjs

<分区>

我有一个输入框。

我需要将这个框自动大写。

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

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

最佳答案

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

//修复光标在最后跳转的bug

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/

相关文章:

javascript - 当我运行 ajaxRequest.open 时,警报 3 没有出现

jquery自动增长文本区域与初始文本

javascript - html中的&lt;script&gt;标签会影响浏览器中html的结果吗?

javascript - 如何防止 Angular 应用程序中路由器链接的默认点击行为?

jquery - 如何使用纯 CSS 而不是 jquery 删除第 2 个 0r 第 4 个 div 填充

JavaScript 函数长度和参数属性/字段

javascript - 通过 fn.apply 或 fn.bind 将函数传递给 setTimeout

javascript - 如何允许缩放平板电脑,而不是移动设备

javascript - 使用 PDFObject 显示加载指示器

javascript - 在 Jquery Mobile 中显示可折叠内容时如何隐藏可折叠标题?