daniela
daniela

Reputation: 43

How to convert text to uppercase while typing in input field using angular js

I know that is posible with jquery but I dont know how to do that with angular js, please any sugestion?

       function mayuscula(campo){
            $(campo).keyup(function() {
                           $(this).val($(this).val().toUpperCase());
            });
       }

Upvotes: 1

Views: 27821

Answers (2)

Mikko Viitala
Mikko Viitala

Reputation: 8404

You could do it in HTML template or via JS using the angular uppercase filter.

<div>
  <label>Input 1</label>
  <input type="text" ng-model="first">{{ first | uppercase }}
</div>

If you need to change the value in-place, use toUpperCase when ever value is changed.

<div>
  <label>Input 1</label>
  <input type="text" ng-model="first" ng-change="text = text.toUpperCase()">
</div>


Above in preferred approaches. Here's yet another way to achieve same result using $watch but this is not recommended. See comments section.

<div>
  <label>Input 2</label>
  <input type="text" ng-model="second">
</div> 

var unwatch = $scope.$watch('second', function(val) {
    $scope.second = $filter('uppercase')(val);
}, true);

$scope.$on('$destroy', unwatch);

Related Plunker here http://plnkr.co/edit/susiRn

Upvotes: 1

Daniel Camboim
Daniel Camboim

Reputation: 86

You can also create a directive for this!

Check the code:

directive('uppercase', function() {
return {
    restrict: "A"
    require: "?ngModel",
    link: function(scope, element, attrs, ngModel) {

        //This part of the code manipulates the model
        ngModel.$parsers.push(function(input) {
            return input ? input.toUpperCase() : "";
        });

        //This part of the code manipulates the viewvalue of the element
        element.css("text-transform","uppercase");
    }
};
})

For its usage, here's an example:

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

Upvotes: 5

Related Questions