AngularJS custom filter for text / number

I am trying to write my first custom filter for AngularJS. I want to determine if something is either a string or a number. If it is a number, it formats it as such with a built-in filter | number | number .

Currently has a workaround using ng-if :

HTML

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

Controller:

 $scope.data = { One:55689, two:"consider all the options", three:800243, four:"all over", five:"or just beginning" }; $scope.isNumber = function (value) { return angular.isNumber(value); }; 

I decided that it would be a better decision to designate it as my own filter. This is what I still have (yes, I know this is bare bones ... this is my first).

 .filter('textOrNumber',function(){ return function (input) { if(typeof input === 'number'){ console.log("I'm a number"); //return as formatted number } else { console.log("Not a number"); //do nothing, just return }; return input; }; }) 

When it will be considered a number, can I just apply the Angular | number | number ? Or do I need to manually make a filter using javascript?

+6
source share
1 answer

I would introduce a $filter service, and then program numerical programming as follows:

 angular.module('filters', []). filter('textOrNumber', ['$filter', function ($filter) { return function (input, fractionSize) { if (isNaN(input)) { return input; } else { return $filter('number')(input, fractionSize); }; }; }]); 

This way you can use your textOrNumber filter as follows:

 {{myText|textOrNumber:4}} 

This is where JSFiddle works.

+17
source

Source: https://habr.com/ru/post/947845/


All Articles