Created
July 11, 2013 16:16
-
-
Save ctesene/5976873 to your computer and use it in GitHub Desktop.
Angular directive to capitalize the first letter of an input field.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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