StrugglingCoder
StrugglingCoder

Reputation: 5021

How to check for a number in AngularJS template HTML

Something weird is happening and I don't why.

In my application for certain conditions, some values are passed as undefined.

So, if a variable is computed like this

selectedPricingMappingObj.forEach(function(server){
    .....
    .....
    vm.totalOfCostCalculationItems += server.details.price;

where price is undefined.

It shows me NaN when price undefined.

But when price is defined', angular.isNumber(vm.totalOfCostCalculationItems) returnstrue`.

enter image description here

But when I try the same in UI.

<td style="text-align:left;"
    ng-if="angular.isNumber(vm.totalOfCostCalculationItems)">
  <b>${{vm.totalOfCostCalculationItems.toFixed(2)}}<b>
</td>

it shows nothing. Why is that?

Upvotes: 3

Views: 4515

Answers (1)

PJDev
PJDev

Reputation: 983

angular.isNumber won't work in ng-if because angular is not a part of the $scope. It's just a global variable. If you really need to use angular.isNumber in the view, you need to make it a part of your ViewModel:

Controller

vm.isNumber = angular.isNumber;

View

<td style="text-align:left;" ng-if="vm.isNumber(vm.totalOfCostCalculationItems)">


Edit

To answer the question about angular.isNumber(NaN) returning true which appeared in the comments, I've made a quick search and found this: https://github.com/angular/angular.js/issues/701 . Although it's a bit illogical to me as well, it seems that this behaviour is consistent with JavaScript standards as typeof NaN === 'number' is also resolved to true. If you want to avoid such behaviour, you need to check the number both with angular.isNumber and !isNaN:

vm.isNumber = function(number) {
    return angular.isNumber(number) && !isNaN(number);
}

Upvotes: 5

Related Questions