Thomas Thomas - 1 month ago 28
AngularJS Question

Comparing date to NaN and undefined

I have a pretty simple if statement but I don't use javascript too much so I think I have made an error somewhere. If you go to my page you can see the value gets alerted as undefined, but a block of code still gets skipped even though the if parameters are

== undefined
. Does it matter that this is an AngularJS app?

web page: http://alainwebdesign.ca/pl2/#/petType

javascript:

$scope.setDate = function (dateSelected) {
alert(dateSelected);
var now = new Date();
$scope.latest = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes());
$scope.hoursAgo = Math.round((($scope.latest - dateSelected) / 3600000) * 100) / 100;
if ($scope.hoursAgo === undefined || $scope.hoursAgo == NaN) {
alert("Please choose a date/time");
}
else {
alert('You lost your pet ' + $scope.hoursAgo + ' hour(s) ago');
$scope.checkDateSet = true;
}
}

Answer

To check if ($scope.hoursAgo === undefined || $scope.hoursAgo == NaN)

write like this

if ($scope.hoursAgo === 'undefined' || isNaN($scope.hoursAgo)) {