Nassim
Nassim

Reputation: 131

compare dates within ng-if angular

I am looking to compare two dates in ng-if this is what my jade file looks like.

html :

<button ng-if="{{product.experationDate}} < {{CurrentDate}}" type="button> 
// do somthing
</button>

javascript :

$scope.CurrentDate = new Date();

and : date_expiration: {type: Date}

but it not work ! any help will be appreciated. thanks

Upvotes: 4

Views: 18428

Answers (3)

Charlie Ng
Charlie Ng

Reputation: 640

I don't think you can compare javascript date type directly. Instead, do this and remove {{}}

<button ng-if="product.experationDate.getTime() < CurrentDate.getTime()" type="button> 
// do somthing
</button>

which compares their milliseconds.

Upvotes: 1

anthares
anthares

Reputation: 11213

You can try with:

<button ng-if="product.experationDate < CurrentDate" type="button> // do somthing </button>

In Angular directives like ng-if, you don't need the {{ }} as the expression is evaluate either way.

Upvotes: 3

rrd
rrd

Reputation: 5957

Don't do this kind of logic in the template. That's what your services and controllers are for. You need to have a method in your controller that returns the boolean:

isExpirationExpired(product) {
  // your date logic here, recommend moment.js;
  return moment(product.experationDate).isBefore(moment(currentdate));
  // or without using moment.js:
  return product.experationDate.getTime() < currentdate.getTime();
  // or using Date
  return new Date(product.experationDate).valueOf() < new Date(currentdate).valueOf();
}

And your template:

ng-if="vm.isExpirationExpired(product)"

Upvotes: 5

Related Questions