Ng show if the variable is a number

All we need is an easy explanation of the problem, so here it is.

I want to display an element only if a value is a number. How to do this? I tried :

  • ng-show='angular.isNumber(10)'
  • ng-show='isNumber(10)'

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Add to your scope:

$scope.isNumber = angular.isNumber;

and then use:

ng-show="isNumber(10)"

http://jsfiddle.net/88wqe/

Method 2

<div ng-controller="Ctrl" ng-show="isNumber(num)">
    AAA
</div>

function Ctrl($scope){
    $scope.num = '10';

    $scope.isNumber= function (n) {
      return !isNaN(parseFloat(n)) && isFinite(n);
    }
}

Here’s a JS Fiddle http://jsfiddle.net/7RD47/

It uses the top answer from Validate decimal numbers in JavaScript – IsNumeric(), which is a more complete way of validating numbers.

Method 3

Try this:

ng-show='isNumeric(10)'

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply