Capital not Capitol.
Angular has some great built in filters, but one case that comes up the Angular doesn’t handle automatically capitalizing the first letter in a string. (Skip to the bottom to get the code snippet if you don’t care about my babbling)
For capitalizing the first letter, but leaving the rest of the string the same, we’ll use the substring, toLowerCase and toUpperCase methods.
I’m assuming you have a module set up, I’m using the app convention.
The regular JavaScript for capitalizing goes like this:
1 2 3 4 5 6 7 8 9 |
var ourString = "string"; allUpper = ourString.toUpperCase(); // This will make a whole string uppercase, result: STRING allLower = ourString.toLowerCase(); // The whole string will be lower case, result: STRING firstUpperDirty = ourString.substring(0, 1).toUpperCase() + ourString.substring(1); //This will make the first letter uppercase, leaving the rest of the string alone. This will yield "String" in this situation, but if you had the the value "strinG" this would result in "StrinG." This might not be what you wanted, so it should not be used if your looking to display the string with only capitalization. |
Notice the substring method treats the string as an array, the first argument in the substring is the index (or start position) and starts counting at zero. The second argument in substring is optional, and tells how many letters/characters you want to count through and send forward into the next method or return.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
//FINALLY, the right way firstUpper = ourString.substring(0, 1).toUpperCase() + ourString.substring(1).toLowerCase(); //We can also make this a function: function firstUpper(ourString) { return ourString.substring(0,1).toUpperCase() + OurString.substring(1).toLowerCase(); } //A more verbose, but a little easier to read: function firstUpper(ourString) { ourString ourString.toLowerCase(); return ourString.substring(0, 1).toUpperCase() + ourString.substring(1); } //Now lets put this into our angular module. app.filter('firstUpper', function() { return function(input, scope) { return input ? input.substring(0,1).toUpperCase()+input.substring(1).toLowerCase() : ""; } }); |
Notice the filter method on app (our module), the first argument is the name and the second is the function. Within, we’re returning another function which takes the input (the value from the template) with the capitalized first letter. Also note, I’ve added in a conditional, dependent on input being defined. That way if there’s no value there it won’t produce an error. In the template we’d include something like this {{ value | firstUpper }}