Skip to content Skip to sidebar Skip to footer

Formatting Data Before Render It

I am displaying some data in the view, but I need to formatted first, I was doing something like val.toFixed(2) and that is OK, it works but the problem is that val sometimes comes

Solution 1:

Create a custom filter to use on your template.

<table>
    <tr><thng-repeat='header in headers'>{{header.th}}</th></tr><tr><tdng-repeat='data in headers'><divng-repeat='inner in data.td'><spanng-repeat='(prop, val) in inner'>{{val|formatValue}}</span></div></td></tr>
</table>


angular.module('whatever').filter('formatValue', function () {
  returnfunction (value) {
    if (isNaN(parseFloat(value))) {
      return value;
    }

    returnparseFloat(value).toFixed(2);
  } 
});

Solution 2:

You can try this :

That is a clean way to render formated data in view using angularjs as MVC frontend framework :

  • Create a filter in your angular application.
  • Include your filter in your index.html.
  • use your filter like this : {{somedata | filterName}}

That is a simple angular filter to solve your problem, hope it will help you :

angular.module('app')
.filter('formatHeader', function() {
    return function(data) {

        if(angular.isNumber(data)) {
            returndata.toFixed(2);
        }

        returndata;
    }
});

And us it like this :

<table><tr><thng-repeat='header in headers'>{{header.th}}</th></tr><tr><tdng-repeat='data in headers'><divng-repeat='inner in data.td'><spanng-repeat='(prop, val) in inner'>{{val | formatHeader}}</span></div></td></tr>

You can take a look about these references :

Post a Comment for "Formatting Data Before Render It"