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

67,179

Solution 1

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

Solution 2

Please remember that not everything needs an Angular solution. You see this a lot with the jQuery crowd; they like to use expensive jQuery functions to do things that are simpler or easier to do with pure javascript.

So while you might very well need a capitalize function and the above answers provide that, it's going to be a lot more efficient to just use the css rule "text-transform: capitalize"

<tr ng-repeat="(key, value) in item">
    <td style="text-transform: capitalize">{{key}}</td>
    <td>{{item}}</td>
</tr>

Solution 3

You can create a custom filter 'capitalize' and apply it to any string you want:

 <div ng-controller="MyCtrl">
     {{aString | capitalize}} !
</div>

JavaScript code for filter:

var app = angular.module('myApp',[]);

myApp.filter('capitalize', function() {
    return function(input, scope) {
        return input.substring(0,1).toUpperCase()+input.substring(1);
    }
});

Solution 4

Modified his code to capitalize every first character of word. If you give 'john doe', output is 'John Doe'

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

Solution 5

Use the CSS :first-letter pseudo class.

You need to put everything lowercase and after apply the uppercase only to the first letter

p{
    text-transform: lowercase;
}
p:first-letter{
    text-transform: uppercase;
}

Here's an example: http://jsfiddle.net/AlexCode/xu24h/

Share:
67,179
Federico Elles
Author by

Federico Elles

Updated on July 09, 2022

Comments

  • Federico Elles
    Federico Elles almost 2 years

    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.

  • tamakisquare
    tamakisquare about 11 years
    I don't think filters can be applied on input field.
  • tamakisquare
    tamakisquare about 11 years
    I don't think filters can be applied on input field.
  • Jason Goemaat
    Jason Goemaat about 11 years
    could you explain a little more how this works or provide links to the docs? Also if you type a lowercase letter at the start and the box is not empty the cursor moves to the end, but if you type an uppercase character it doesn't...
  • Mark Rajcok
    Mark Rajcok about 11 years
    @JasonGoemaat, docs.angularjs.org/guide/forms#customvalidation I don't have any ideas on how to fix the cursor movement.
  • Chris Bier
    Chris Bier over 10 years
    The OP only wants to capitalize the first letter in the input. This solution capitalizes each word
  • Chris Bier
    Chris Bier over 10 years
    The OP only wants to capitalize the first letter in the input. This solution capitalizes each word
  • Aditya M P
    Aditya M P over 10 years
    Ain't that such a shame, @tamakisquare; I came here googling for exactly that.
  • James
    James over 10 years
    @JasonGoemaat The cursor movement occurs because the content is being replaced by the changed text (only changed when first letter is entered as non-capital). To fix this you can capture the selection range and reset the new selection range within the new text once it is set. There is a sweet library called Rangy (code.google.com/p/rangy) that will help you with this if you are serious enough about it to fix it.
  • AlexCode
    AlexCode about 10 years
    No, I'm afraid not. This applies to content, not to specific properties of an element. On Inputs I'm afraid you have to use javascript.
  • oma
    oma about 10 years
    good thoughts, but this wouldn't necessarily work for input fields, if it is submitted (enter input, click save, for instance), I just got bitten by that.
  • adamdport
    adamdport about 10 years
    In my case, I landed on this question looking for a "force lowercase" solution. Thanks for posting this even though it wasn't a perfect solution to the OP.
  • Andi
    Andi almost 10 years
    scope[attrs.ngModel] wont work for: <input type="text" ng-model="myObj.user.name" capitalize-first> as attrs.ngModel evaluates to "myObj.user.name" so scope[attrs.ngModel] evaluates to undefined.
  • Mark Rajcok
    Mark Rajcok almost 10 years
    @Andi, good catch. I updated the answer and fiddle to use $parse, which will handle the original case and your scenario.
  • Sunday G Akinsete
    Sunday G Akinsete almost 10 years
    How do you do this for multiple words in a sentence?
  • Blazemonger
    Blazemonger almost 10 years
    Can someone explain why this is better (or worse) than setting a $watch in the controller? Assuming one only needs to use it one time.
  • xpepermint
    xpepermint almost 10 years
    That does not play well with $asyncValidators or ng-model-options="{ debounce: 1000 }".
  • Ted Pennings
    Ted Pennings over 9 years
    Uppercase is all caps.
  • marc carreras
    marc carreras about 9 years
    when using $setViewValue, you trigger the parsers and validators again. If you add a console.log statement at the beginning of your capitalize function, you'll see it printed twice
  • Nicholas
    Nicholas about 9 years
    I changed the capitalized variable so it would lowercase the rest of the string: var capitalized = inputValue.charAt(0).toUpperCase() + inputValue.substring(1).toLowerCase();
  • Tushar Shukla
    Tushar Shukla over 7 years
    Just what i needed!! Thanks!
  • AkRoy
    AkRoy about 6 years
    This makes entire text capital. Am looking for only first letter to be capital. And cursor to be remained in its position
  • AkRoy
    AkRoy about 6 years
    Can you please give some more detail
  • Mattias
    Mattias almost 4 years
    @ChrisBier, I think you're confusing capitalize with uppercase. css-tricks.com/almanac/properties/t/text-transform