jeudi 7 mai 2015

How to catch null, undefined, blank values with AngularJS filter

I'm attempting to write a filter for use in a grid that will catch all null, undefined, blank string, or other similar values and display a dash "-". I've written the following so far, but it doesn't catch null values, and I'm wondering if it could be more succinct and possibly refactored to avoid three layers of nested if/else statements. Percentage values need to be checked that they're over 0 and under 1. Also, negative numbers and 0's should be returned as is. Thanks!

angular.module('AdverseEventsExplorer.main').filter('emptyCellFilter', function ($filter) {
    return function (input, cellFilter, args1, args2) {    

        if (cellFilter == undefined) {
            return (angular.isNumber(input) || angular.isDefined(input) && input.length > 0) ? input : '-';
        } else {
            if (cellFilter.match(/pctg|percent|pctgFilter|incidence/ig)) {
                return (input > 0 && input < 1.0000000) ? $filter(cellFilter)(input, args1, args2) : '-';
            } else {
                return (angular.isNumber(input) || angular.isDefined(input) && input.length > 0) ? input : '-';
            }
        }

    };
});

Version 2.0 taking into account @tymeJV's comment:

angular.module('AdverseEventsExplorer.main').filter('emptyCellFilter', function ($filter) {
    return function (input, cellFilter, args1, args2) {

        if (!cellFilter) {
            return (angular.isNumber(input) || (input)) ? input : '-';
        } else {
            if (cellFilter.match(/pctg|percent|pctgFilter|incidence/ig)) {
                return (input > 0 && input < 1.0000000) ? $filter(cellFilter)(input, args1, args2) : '-';
            } else {
                return (angular.isNumber(input) || (input)) ? $filter(cellFilter)(input, args1, args2) : '-';
            }
        }

    };
});

Aucun commentaire:

Enregistrer un commentaire