Skip to content

Instantly share code, notes, and snippets.

@ctesene
Created July 11, 2013 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctesene/5976873 to your computer and use it in GitHub Desktop.
Save ctesene/5976873 to your computer and use it in GitHub Desktop.
Angular directive to capitalize the first letter of an input field.
angular.module('MyApp').directive("capitalizeFirstLetter",
['$',
function ($) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs) {
var wasCapitalized = false;
function capitalizeFirstLetter() {
var currentValue = element.val();
if (!currentValue) {
return;
}
if (wasCapitalized) {
return;
}
if (currentValue.length === 1) {
var newValue = capitalize(currentValue);
wasCapitalized = true;
element.val(newValue);
scope.$apply();
}
}
function capitalize(item) {
return itemIsLowerCaseLetter(item) ? item.toUpperCase() : item;
}
function itemIsLowerCaseLetter(item) {
return item.toUpperCase().toLowerCase() === item;
}
element.bind('keypress', capitalizeFirstLetter);
}
};
}
]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment