Conditionally apply filters with ng-repeat

I have an object that contains a mixture of numbers and text for values. I would like to apply the numbers filter to the value of an object when that number is (obviously). But, when it's not a number, I would be fine just spitting out a string. As with application | number | number to value formats numbers, but leaves string values ​​empty (after that they are not numbers).

I assume this should be a custom filter (which I still need to do). Is there a way to do this exclusively in HTML when you do ng-repeat ?

 <table> <tr ng-repeat="(metric, metricData) in data"> <td>{{metric}}</td> <td>{{metricData | number}}</td> </tr> </table> $scope.data = { name:"this is the name", score:48 outcome:"as expected", attendance:820, total:212.34 }; 
+8
angularjs filter angularjs-ng-repeat
Jun 20 '13 at 5:38 on
source share
3 answers

Here is the requested alternative version of the answer from @callmekatootie using ng-if (v1.1.5):

 <table> <tr ng-repeat="(metric, metricData) in data"> <td>{{metric}}</td> <td ng-if="isNumber(metricData)">{{metricData | number}}</td> <td ng-if="!isNumber(metricData)">{{metricData}}</td> </tr> </table> 

This has the advantage that only the filter works on elements that are numeric. In this case, this is probably of little use, but may be useful in other more complex filter situations. To answer your other question about the built-in angular.isNumber , @callmekatootie uses it in the scope function isNumber , which is just a wrapper for using the built-in in the view.

Here is the fiddle

+18
Jun 20 '13 at 23:21
source share
— -

You can try it this way: in your controller you can have a function that identifies whether the provided value is a string or a number:

 $scope.isNumber = function (value) { return angular.isNumber(value); }; 

Then, in your opinion, you can get the following:

 <table> <tr ng-repeat="(metric, metricData) in data"> <td>{{metric}}</td> <td ng-show="isNumber(metricData)">{{metricData | number}}</td> <td ng-hide="isNumber(metricData)">{{metricData}}</td> </tr> </table> 

Thus, when metricData is a number, it is filtered and when it is a string, it is displayed as is.

+3
Jun 20 '13 at 6:23
source share

I know this is old, but I think the best solution is to switch logic to filter.

 app.filter("metricDataFilter", function($filter) { return function(value) { if(angular.isNumber(value)) { return $filter("number", value); } return value; } } 

This way the HTML is shorter and angular won't have to redraw the dom elements

 <table> <tr ng-repeat="(metric, metricData) in data"> <td>{{metric}}</td> <td>{{metricData | metricDataFilter}}</td> </tr> </table> 
+3
Dec 05 '15 at 13:24
source share



All Articles