AngularJS – Format Text Return From JSON To Title Case

All we need is an easy explanation of the problem, so here it is.

I have a service that retrieves data from a JSON file.

Some of the data within the data is all in uppercase, for example:

$scope.FootballClubs = [{
    CompanyName: [MANCHESTER UNITED, LIVERPOOL FOOTBALL CLUB, CHELSEA, WIGAN UNTIED, LEICESTER CITY]
}];

And in my HTML, i am simply throwing about the above:

<div ng-repeat="name in FootballClubs">
    {{ name.CompanyName }}
</div>

Which throws out:

MANCHESTER UNITED
LIVERPOOL FOOTBALL CLUB
CHELSEA
WIGAN UNTIED
LEICESTER CITY

What i am trying to display is:

Manchester United
Liverpool Football Club
Chelsea
Wigan United
Leicester City

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

A filter is an ideal solution for this purpose

<div ng-repeat="name in FootballClubs">
    {{ name.CompanyName | titleCase }}
</div>

So the filter itself would be

angular.module('myFootballModule', [])
  .filter('titleCase', function() {
    return function(input) {
      input = input || '';
      return input.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    };
  })

Method 2

Let me offer a non-directive way which is probably easier to implement but less powerful and dependent on the solution being UI only. First, change them to lowercase {{name.CompanyName.toLowerCase()}}

I think the easiest way is to just have CSS format it (either via a style tag, class, etc).

<div ng-repeat="name in FootballClubs" style="text-transform:capitalize;">
 {{ name.CompanyName.toLowerCase() }}
</div>

Here is a demo: http://plnkr.co/edit/S4xtIRApMjKe0yQGREq5?p=preview

Method 3

just use this div in your HTML

  <div ng-repeat="name in FootballClubs">
     {{ name.CompanyName | titleCase:CompanyName }}
 </div>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply