Monday, September 8, 2014

Formatting currency, number using Angular filters in templates

<html ng-app="countryApp">
  <head>
    <meta charset="utf-8">
    <title>Angular.js Example</title>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <script>
      var countryApp = angular.module('countryApp', []);
      countryApp.controller('CountryCtrl', function ($scope, $http){
        $http.get('countries.json').success(function(data) {
          $scope.countries = data;
        });
      });
    </script>
  </head>
  <body ng-controller="CountryCtrl">
    <table>
      <tr>
        <th>Country</th>
        <th>Population</th>
        <th>Flag</th>
        <th>Capital</th>
        <th><a href="http://en.wikipedia.org/wiki/List_of_countries_by_GDP_(PPP)">GDP (PPP)</a></th>
      </tr>
      <tr ng-repeat="country in countries">
        <td>{{country.name}}</td>
        <td>{{country.population | number }}</td>
        <td><img ng-src="{{country.flagURL}}" width="100"></td>
        <td>{{country.capital}}</td>
        <td>{{country.gdp | currency }}</td>
      </tr>
    </table>
  </body>
</html>
countries.json

[
  {
    "name": "China",
    "population": 1359821000,
    "flagURL": "//upload.wikimedia.org/wikipedia/commons/f/fa/Flag_of_the_People%27s_Republic_of_China.svg",
    "capital": "Beijing",
    "gdp": 12261
  },
  {
    "name": "India",
    "population": 1205625000,
    "flagURL": "//upload.wikimedia.org/wikipedia/en/4/41/Flag_of_India.svg",
    "capital": "New Delhi",
    "gdp": 4716
  },
  {
    "name": "United States of America",
    "population": 312247000,
    "flagURL": "//upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg",
    "capital": "Washington, D.C.",
    "gdp": 16244
  }
]

No comments: