Last active
May 27, 2016 08:20
-
-
Save tucq88/413aed2db713486cb7aa4298269af326 to your computer and use it in GitHub Desktop.
AngularJS | Directive | Capitalize first word or make first char uppercase
This file contains hidden or 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
| 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