I am trying to convert my date in ng-repeat to age.
But when I use a scope in my controller:
$scope.calculateAge = function(birthday) {
var ageDifMs = Date.now() - new Date(birthday);
var ageDate = new Date(ageDifMs);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Or when I use filter:
myApp.filter('ageFilter', function() {
function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
return function(birthdate) {
return calculateAge(birthdate);
};
});
With this HTML:
<div ng-repeat="user in users | limitTo:20" class="col-50">
<div class="memba-picture" style="background:url({{ user.picture }}">
<div class="memba-gradient"><i class="fa fa-check memba-wanted"></i></div>
<span class="memba-title">{{user.first_name}}</span>
<p class="memba-age">{{user.more.birthday | ageFilter}} Ans</p> <!-- Or calculateAge -->
</div>
</div>
It doesn't work. But when I get date with scope in my controller, it works. I think it's maybe because when I get date, I convert it with good format:
userRef.child(birthday).once('value', function(snap) {
$scope.birthday = new Date(snap.val());
})
How can I get the age correctly?
Thanks.
Thanks to the solution given by PixelBits at this question, I was able to solve my problem. Here is how I proceeded:
Controller:
$scope.calculateAge = function calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
HTML
{{ calculateAge(user.more.birthday) }}
Thank you all !