3

如何使用 ng-if 实现检查 angularJS 中的空日期?

HTML 源代码是

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="customersCtrl"> 

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>D.O.B</th>
        </tr>
    </thead>
  <tr ng-repeat="x in names>
    <td>{{ x.Name }}</td>
    <td><span ng-if="x.DOB != null">{{ formatDate(x.DOB) |  date:'dd-MM-yyyy' }}</span></td>
  </tr>
</table>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {

    $scope.names = [
        { Name: 'Jani', DOB: '' },
        { Name: 'Hege', DOB: '1995-05-07' },
        { Name: 'Kai', DOB: '1995-08-24' }
    ];

    $scope.formatDate = function (date) {
        return new Date(date);
    };

});
</script>

</body>
</html>

在这里,我希望使用 angularJS ng-if消除日期值等于nullNaN-NaN-0NaN

在上面的源代码中没有执行 IF 条件

4

2 回答 2

4

您可以使用ng-if="x.DOB",因为空字符串或未定义将返回 false

plnkr

于 2015-12-08T10:17:59.030 回答
1

尝试使用这个:

<td>
 <span ng-if="x.DOB != ''">{{ formatDate(x.DOB) |  date:'dd-MM-yyyy' }}
</span>
</td>

DOB= " "; 表示将空String赋值给DOB并且DOB = null;表示将 (null) 或“根本没有值”分配给DOB

更新:

<span ng-if="x.DOB">{{ formatDate(x.DOB) |  date:'dd-MM-yyyy' }}
    </span>
于 2015-12-08T10:15:59.660 回答