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?