3

I have one division in my modal ,I only required to show the div when the value of a variable $scope.ornamentweightinbank is not equal to NaN.

<div class="rows container-fluid" ng-if="ornamentweightinbank!==NaN">

Is this the conventional way to deal with NaN

Ajith
  • 775
  • 1
  • 13
  • 47

2 Answers2

2

You can access JavaScript's native isNaN function by creating a similar function on this within your controller, you can then access it in your ngIf directive like so:

(function() {

  'use strict';

  angular.module('app', []);

})();

(function() {

  'use strict';

  angular.module('app').controller('MainController', MainController);

  MainController.$inject = ['$scope', '$timeout'];

  function MainController($scope, $timeout) {

    // make isNaN available in your view via controller as syntax
    this.isNaN = function(value) {

      return isNaN(value);

    }

    // set ornamentweightinbank to a number
    $scope.ornamentweightinbank = 10;

    // for demonstrative purposes set ornamentweightinbank to NaN after 5 seconds
    $timeout(function() {

      $scope.ornamentweightinbank = 10 * "test";

    }, 5000);

  }

})()
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>

<div ng-app="app" ng-controller="MainController as MainCtrl">

  <div class="rows container-fluid" ng-if="!MainCtrl.isNaN(ornamentweightinbank)">
    This will show if ornamentweightinbank is not equal to NaN
  </div>

  <div class="rows container-fluid" ng-if="MainCtrl.isNaN(ornamentweightinbank)">
    This will show if ornamentweightinbank is equal to NaN
  </div>

</div>

Please see this stackoverflow answer why you cannot directly use isNaN in your expression.

Community
  • 1
  • 1
cnorthfield
  • 3,384
  • 15
  • 22
0

There is one way where in you can make the isNaN function available in html i.e. by assigning it in scope/this of the current controller.

this.isNaN = function(value){ //or $scope.isNaN = function(value){
return isNaN(value);
}

which when used in HTML,

<span ng-class="{'color-red':!isNaN(value)}" ng-bind="value"></span>

I suppose for any kind of Javascript Native functions which I might require inside HTML, I prefer making a copy of windows object in rootScope.

$rootScope.windowInstance = window;

this will allow us to use any kind of window functions in html,

<span 
ng-class="{'color-red' : !windowInstance['isNaN'](value) && windowInstance['parseFloat'](value) < 0}" 
ng-bind="value">
</span>
<!-- Will color the value red when the value is Number and negative -->
RGTest
  • 80
  • 12