0

I have several brief Angularjs expressions on a page which perform some basic arithmetic with a value. Because of the arithmetic, they always evaluate to null, until a value has been passed. I realise this may not be the best way to approach this problem, and am open to suggestions, but I think for this scenario I would simply like to know how to hide the NaN's from the view.

{{myItem.value / 4}}

I have tried the solution mentioned here but I think my case is different because the math is being evaluated each time, thus returning NaN, not a number, (null).

user43633
  • 309
  • 3
  • 7

2 Answers2

2

Try like this

<div ng-hide="!(myItem.value / 4)">
  {{myItem.value / 4}}
</div>
Anik Islam Abhi
  • 24,324
  • 8
  • 52
  • 74
  • The ability to evaluate expressions inside the assignment is so useful! I did not know it could be done. – user43633 Nov 22 '15 at 10:17
0

Create a filter:

app.filter('divide', function() {
    function isNumeric(n) {
       return !isNaN(parseFloat(n)) && isFinite(n);
    }

    return function(value, arg) {
        if (isNumeric(value) && isNumeric(arg))
           return parseFloat(value)/parseFloat(arg);

        return value;
    }
});

Usage:

{{ myItem.Value | divide: 4 }}

If either myItem.Value or the argument passed to the divide filter is not numeric (or undefined), then it will simply return original value unaltered.

If you want to hide the value if it is undefined or not numeric, then a filter helps you out again:

app.filter('numberDefault', function() {
    return function(value, defaultValue) {
        function isNumeric(n) {
           return !isNaN(parseFloat(n)) && isFinite(n);
        }

        if (isNumeric(value))
           return parseFloat(n);

        return defaultValue;
    }
});

Then you can chain them:

{{ myItem.Value | numberDefault:'' | divide: 4 }}

If myItem.Value is not numeric, the numberDefault will return an empty string. The empty string when passed to the divide filter will just return the original value, an empty string.

pixelbits
  • 48,078
  • 15
  • 86
  • 124