How to autocapitalize the first character in an input field in AngularJS?
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>
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/
Federico Elles
Updated on July 09, 2022Comments
-
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 about 11 yearsI don't think filters can be applied on input field.
-
tamakisquare about 11 yearsI don't think filters can be applied on input field.
-
Jason Goemaat about 11 yearscould 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 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 over 10 yearsThe OP only wants to capitalize the first letter in the input. This solution capitalizes each word
-
Chris Bier over 10 yearsThe OP only wants to capitalize the first letter in the input. This solution capitalizes each word
-
Aditya M P over 10 yearsAin't that such a shame, @tamakisquare; I came here googling for exactly that.
-
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 about 10 yearsNo, 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 about 10 yearsgood 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 about 10 yearsIn 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 almost 10 yearsscope[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 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 almost 10 yearsHow do you do this for multiple words in a sentence?
-
Blazemonger almost 10 yearsCan 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 almost 10 yearsThat does not play well with
$asyncValidators
orng-model-options="{ debounce: 1000 }"
. -
Ted Pennings over 9 yearsUppercase is all caps.
-
marc carreras about 9 yearswhen 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 about 9 yearsI 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 over 7 yearsJust what i needed!! Thanks!
-
AkRoy about 6 yearsThis makes entire text capital. Am looking for only first letter to be capital. And cursor to be remained in its position
-
AkRoy about 6 yearsCan you please give some more detail
-
Mattias almost 4 years@ChrisBier, I think you're confusing capitalize with uppercase. css-tricks.com/almanac/properties/t/text-transform