Capitalize the first letter of string in AngularJs

137

I want capitalize first character of string in angularjs

As i used {{ uppercase_expression | uppercase}} it convert whole string to upper case.

This question is tagged with javascript angularjs filter uppercase capitalize

~ Asked on 2015-05-13 06:32:43

The Best Answer is


236

use this capitalize filter

_x000D_
_x000D_
var app = angular.module('app', []);_x000D_
_x000D_
app.controller('Ctrl', function ($scope) {_x000D_
   $scope.msg = 'hello, world.';_x000D_
});_x000D_
_x000D_
app.filter('capitalize', function() {_x000D_
    return function(input) {_x000D_
      return (angular.isString(input) && input.length > 0) ? input.charAt(0).toUpperCase() + input.substr(1).toLowerCase() : input;_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="app">_x000D_
    <div ng-controller="Ctrl">_x000D_
        <p><b>My Text:</b> {{msg | capitalize}}</p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

~ Answered on 2015-05-13 06:36:25


151

I'd say don't use angular/js as you can simply use css instead:

In your css, add the class:

.capitalize {
   text-transform: capitalize;
}

Then, simply wrap the expression (for ex) in your html:

<span class="capitalize">{{ uppercase_expression }}</span>

No js needed ;)

~ Answered on 2016-04-05 12:51:20


Most Viewed Questions: