Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS custom filter for text/number

I'm attempting to write my first custom filter for AngularJS. I want the ability to identify if something is either a string or number. If it's a number, it formats it as such with the built-in filter | number.

I currently have 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 figured it'd be a better solution to assign it as it's own filter though. This is what I have so far (yes I know it's the bare bones... it's my first one).

.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 validates to be a number, can I just have it apply the Angular | number filter? Or do I need to manually do the filter with javascript myself?

like image 329
EnigmaRM Avatar asked Jun 21 '13 15:06

EnigmaRM


1 Answers

I would inject $filter service and then call number filter programatically like this:

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 will be able to use your textOrNumber filter like this:

{{myText|textOrNumber:4}}

Here is working JSFiddle.

like image 130
PrimosK Avatar answered Sep 21 '22 18:09

PrimosK