Oam Psy Oam Psy - 5 months ago 21
AngularJS Question

AngularJS - Format Text Return From JSON To Title Case

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

Answer

Filer is ideal solution for this purpose:

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

So filter itself would be like:

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();});
    };
  })
Comments