javascript - angularjs 在文本框中强制大写

标签 javascript angularjs uppercase angularjs-filter

我试过使用大写过滤器,但它不起作用。我试过两种方法:

<input type="text" ng-model="test" uppercase/>

<input type="text" ng-model="{{test | uppercase}}"/>

第二个触发 javascript 错误:

Syntax Error: Token 'test' is unexpected, expecting [:]

我希望当用户在文本框中键入时将文本强制为大写。

我该怎么做?

最佳答案

请看下面的另一个答案,它比这个更好。

此答案基于此处的答案:How to autocapitalize the first character in an input field in AngularJS? .

我想你想要的是这样的解析器函数:

angular
  .module('myApp', [])
  .directive('capitalize', function() {
    return {
      require: 'ngModel',
      link: function(scope, element, attrs, modelCtrl) {
        var capitalize = function(inputValue) {
          if (inputValue == undefined) inputValue = '';
          var capitalized = inputValue.toUpperCase();
          if (capitalized !== inputValue) {
            // see where the cursor is before the update so that we can set it back
            var selection = element[0].selectionStart;
            modelCtrl.$setViewValue(capitalized);
            modelCtrl.$render();
            // set back the cursor after rendering
            element[0].selectionStart = selection;
            element[0].selectionEnd = selection;
          }
          return capitalized;
        }
        modelCtrl.$parsers.push(capitalize);
        capitalize(scope[attrs.ngModel]); // capitalize initial value
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <input type="text" ng-model="name" capitalize>
</div>

关于javascript - angularjs 在文本框中强制大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16388562/

相关文章:

javascript - jquery 函数不适用于通过 innerHTML 写入的元素

javascript - 按 list.id 对无序列表的按钮进行排序

javascript - 从具有特定值的二维数组中的行返回值 - 在 Google 脚本中以 HTML 形式列出结果

javascript - 对以整数开头的哈希值进行过滤/排序时出现 Angular $parse 错误

postgresql - postgresql中如何判断一个字符是大写还是小写?

javascript - key 在 firebase 上重复

javascript - 如何对动态生成的文本框进行验证?

angularjs - 将数据从一种状态传递到另一种状态

Java使用递归将输入更改为大写

fonts - wxPython TextCtrl 转换为大写