maikelm maikelm - 4 months ago 24
Javascript Question

Apply filter if value is a number using angularJS

I have this structure in a controller in angularjs:

$scope.modelInfo = {"key1":value1, "key2": value2,.....};


In the view:

<tr ng-repeat="(key,value) in modelInfo">
<td width="60%">{{key}}</td>
<td>{{value}}</td>
</tr>


I need if
typeof value
is number, print value with angular filter, something like:

{{value | number : 4}}

Answer

You can write a custom filter to achieve this:

myApp.filter('myNumber', function($filter) {
    return function(value, fractionSize) {
        if (!angular.isNumber(value)) {
            return value;
        }

        return $filter('number')(value, fractionSize);
    }
});

And then use it:

{{value | myNumber : 4}}

See a working example below:

var app = angular.module("sa", []);

app.controller("FooController", function($scope) {
$scope.modelInfo = {"key1":'value1', "key2": 2.453434};
});

app.filter('myNumber', function($filter) {
  return function(value, fractionSize) {
    if (!angular.isNumber(value)) {
      return value;
    }

    return $filter('number')(value, fractionSize);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="sa" ng-controller="FooController">
  <table>
    <tr ng-repeat="(key,value) in modelInfo">
      <td width="60%">{{key}}</td>
      <td>{{value | myNumber : 4}}</td>
    </tr>
  </table>
</div>

Comments