Skip to content

Instantly share code, notes, and snippets.

@tucq88
Last active May 27, 2016 08:20
Show Gist options
  • Select an option

  • Save tucq88/413aed2db713486cb7aa4298269af326 to your computer and use it in GitHub Desktop.

Select an option

Save tucq88/413aed2db713486cb7aa4298269af326 to your computer and use it in GitHub Desktop.
AngularJS | Directive | Capitalize first word or make first char uppercase
app.directive('capitalize', function($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
//Process input + return processed value
var capitalize = function(inputValue) {
if (inputValue) {
//Capitalize first word
var capitalized = inputValue.charAt(0).toUpperCase() + inputValue.substring(1);
//Capitalize all words (after space)
//var capitalized = inputValue.replace(/^(.)|\s(.)/g, function(v) { return v.toUpperCase(); });
if (capitalized !== inputValue) {
ngModel.$setViewValue(capitalized);
ngModel.$render();
}
return capitalized;
}
};
//Push process function to model
//Apply it right now
var model = $parse(attr.ngModel);
ngModel.$parsers.push(capitalize);
capitalize(model(scope));
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment