Rghav
Rghav

Reputation: 33

Format the data dynamically in Angularjs

I am currently working on developing a grid component using HTML / AngularJS. The column data are rendered dynamically.

I am trying to format the data displayed based on the dataType. The data types could be like currency / date / number format. Conceptually, I am trying to achieve like the below one.

Is it possible?

<td ng-repeat="row in rows" title="{{row.toolTip}}">
   {{row.displayData | row.dataType: row.format}}
</td>

Upvotes: 3

Views: 1107

Answers (1)

user2314737
user2314737

Reputation: 29307

Format your data with AngularJS filters

AngularJS provides some filters: currency, lowercase, uppercase (http://www.w3schools.com/angular/angular_filters.asp) or you can define your own filter

Example:

var app = angular.module('myApp', []);
app.controller("myCtrl", function($scope) {
  $scope.data = [{
    name: "Item1",
    price: 50.3
  }, {
    name: "Item2",
    price: 15.55
  }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<style>
  table,
  th,
  td {
    border: 1px solid grey;
    border-collapse: collapse;
    padding: 5px;
  }
  table tr:nth-child(odd) {
    background-color: #f1f1f1;
  }
  table tr:nth-child(even) {
    background-color: #ffffff;
  }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">

    <table>
      <tr ng-repeat="x in data">
        <td>{{ x.name }}</td>
        <td>{{ x.price | currency }}</td>
      </tr>
    </table>

  </div>

Here I modified the W3schools example using a conditional in the ng-style definition to change the CSS style

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<style>
  table,
  th,
  td {
    border: 1px solid grey;
    border-collapse: collapse;
    padding: 5px;
  }
  table tr:nth-child(odd) {
    background-color: #f1f1f1;
  }
  table tr:nth-child(even) {
    background-color: #ffffff;
  }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="customersCtrl">

    <table>
      <tr ng-repeat="x in names" ng-style="{'background-color':(x.Country == 'UK')?'blue':'gray'}">
        <td>{{ x.Name }}</td>
        <td>{{ x.Country }}</td>
      </tr>
    </table>

  </div>

  <script>
    var app = angular.module('myApp', []);
    app.controller('customersCtrl', function($scope, $http) {
      $http.get("http://www.w3schools.com/angular/customers.php")
        .success(function(response) {
          $scope.names = response.records;
        });
    });
  </script>

Upvotes: 1

Related Questions