6

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?

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That is precisely correct. I knew it could be as simple as this. I haven't looked at $filter. I'll have to do that to better understand what it is capable of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.