How to autocapitalize the first character in an input field in AngularJS?
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
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/
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>
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);
}
});