angularjs force uppercase in textbox

前端 未结 14 1789
情歌与酒
情歌与酒 2020-11-30 20:47

I\'ve tried using the uppercase filter but it does not work. I\'ve tried doing it two ways:


<         


        
14条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 21:03

    Please see the other answer below, which is superior to this one.

    this answer is based on the answer here: How to autocapitalize the first character in an input field in AngularJS?.

    I'd imagine that what you'd want would be a parser function like this:

    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
          }
        };
      });
    
    
    

提交回复
热议问题