小编典典

angularjs在文本框中强制大写

angularjs

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

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

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

第二个触发JavaScript错误:

语法错误:令牌’test’是意外的,预期为[:]

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

我怎样才能做到这一点?


阅读 319

收藏
2020-07-04

共1个答案

小编典典

请参阅下面的另一个答案,该答案优于此答案。

此答案基于以下答案:如何在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>
2020-07-04