How to autocapitalize the first character in an input field in AngularJS?

Federico Elles picture Federico Elles · Mar 6, 2013 · Viewed 66.1k times · Source

How to autocapitalize the first character in an input field inside an AngularJS form element?

I saw the jQuery solution already, but believe this has to be done differently in AngularJS by using a directive.

Answer

Mark Rajcok picture Mark Rajcok · Mar 6, 2013

Yes, you need to define a directive and define your own parser function:

myApp.directive('capitalizeFirst', function($parse) {
   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {
        var capitalize = function(inputValue) {
           if (inputValue === undefined) { inputValue = ''; }
           var capitalized = inputValue.charAt(0).toUpperCase() +
                             inputValue.substring(1);
           if(capitalized !== inputValue) {
              modelCtrl.$setViewValue(capitalized);
              modelCtrl.$render();
            }         
            return capitalized;
         }
         modelCtrl.$parsers.push(capitalize);
         capitalize($parse(attrs.ngModel)(scope)); // capitalize initial value
     }
   };
});

HTML:

<input type="text" ng-model="obj.name" capitalize-first>

Fiddle