nimrod
nimrod

Reputation: 5732

Compare dates in Angular JS

I would like to check if a campaign is currently active or not. The dates deal.Campaign.start and deal.Campaign.end are strings from my backend, now is a date object. How can I cast the strings to date objects in the HTML file?

Ideally I would create the date objects in the controller, but this does not work as I loop over the objects in the HTML file.

controller.js:

$scope.now = new Date();

HTML:

<span ng-repeat="deal in deals"> 
    <span ng-show="deal.Campaign.start < now && deal.Campaign.end > now">
        <span>Active</span>
    </span>
</span>

Upvotes: 1

Views: 2911

Answers (1)

sg.cc
sg.cc

Reputation: 1816

The way I would resolve this is turn all Dates into ms strings:

$scope.now = new Date().getTime();

And same with your other dates:

$scope.deal.Campaign.start = Date.parse($scope.deal.Campaign.start);

This way you would be simply comparing numbers.

Considering ng-repeat, this is still doable, though through a function:

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

And in your HTML:

<span ng-show="formDate(deal.Campaign.start) < now && formDate(deal.campaign.end) > now">

Upvotes: 1

Related Questions