directive to put input fields in uppercase with Angularjs

Asked

Viewed 1,403 times

0

I created the following directive, so when a user type in the input is converted to uppercase, however, when I need to edit this field to insert a word in the middle of what I had already typed it plays the mouse cursor at the end of the input word.

Ex: Teste0 Teste2 When I enter another word Teste0 Teste1 Teste2 it plays the course to the end of Teste2 getting Teste0 Teste2teste1.

return {
         require: 'ngModel',
         link: function(scope, element, attrs, modelCtrl) {
            var capitalize = function(inputValue) {
               if(inputValue === undefined) inputValue = '';
               var capitalized = inputValue.toUpperCase();
               if(capitalized !== inputValue) {
                   modelCtrl.$setViewValue(capitalized);
                   modelCtrl.$render();
                }         
                return capitalized;
             };
             modelCtrl.$parsers.push(capitalize);
             capitalize(scope[attrs.ngModel]);  // capitalize initial value
        }
       };

2 answers

1

If the sole purpose of the directive is to turn the text into uppercase, you can use a css:

.uppercase { 
    text-transform: uppercase; 
}

CSS is lighter than Angularjs and the result will be the same.

0

@Felipe j.we read,

HTML

<div ng-app="meuApp">
    <input type="text" ng-model="name" capitalizado/>         
</div>

Javascript

angular.module('componente', [])
   .directive('capitalizado', function() {
    return {
        require: 'ngModel',        
        link: function(scope, element, attrs, modelCtrl) {
            element.css("text-transform","capitalize");
        }
    };
});

angular.module('meuApp', ['componente']);

JSFIDDLE

  • It worked, but I had to put this: element.css("text-Transform","uppercase");

  • Capitalize leaves only the first letter uppercase.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.