在条件下使用NaN

时间:2017-03-25 14:57:01

标签: angularjs

我的模态中有一个除法,我只需要在变量<?php $request = new FacebookRequest( $session, 'GET graph.facebook.com', '/me', array( 'fields' => 'id,name,photos{album}' ) ); $response = $request->execute(); $graphObject = $response->getGraphObject(); /* handle the result */ ?> 的值不等于$scope.ornamentweightinbank时显示div。

NaN

这是处理<div class="rows container-fluid" ng-if="ornamentweightinbank!==NaN">

的传统方式吗?

2 个答案:

答案 0 :(得分:2)

您可以通过在控制器中的this上创建类似的功能来访问JavaScript的原生isNaN功能,然后您可以在ngIf指令中访问它,如下所示:< / p>

&#13;
&#13;
(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);

  }

})()
&#13;
<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>
&#13;
&#13;
&#13;

请参阅this stackoverflow answer为什么您无法在表达式中直接使用isNaN

答案 1 :(得分:0)

有一种方法可以在html中使isNaN功能可用,即通过在当前控制器的范围/当中分配它。

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

,在HTML中使用时,

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

我想我可能需要在HTML中使用任何类型的Javascript Native函数,我更喜欢在rootScope中复制windows对象。

$rootScope.windowInstance = window;

这将允许我们在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 -->