1

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>

1 Answer 1

1

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">
Sign up to request clarification or add additional context in comments.

4 Comments

I am looping over deals in the HTML file. How can I do this there?
Ah, missed the ng-repeat. Updating answer (though it might be a little less pretty)
Can you guarantee that Date.parse will correctly parse the format provided, especially since "…strings from my backend" could be anything and Date.parse is almost entirely implementation dependent?
I'm uncertain of the significance of that question. If a standard date is stored in a standard format in the backend (like miliseconds from Linux epoch), shouldn't all major browser implementations of Date recognize this? If not, then you could write your own date parsing function, I suppose.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.