0

我試圖將ng-repeat中的日期轉換爲年齡。轉換日期到ng-repeat的年齡

但是,當我用我的控制器範圍:

$scope.calculateAge = function(birthday) { 
    var ageDifMs = Date.now() - new Date(birthday); 
    var ageDate = new Date(ageDifMs); 
    return Math.abs(ageDate.getUTCFullYear() - 1970); 
} 

或當我使用過濾器:

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); 
     }; 
     }); 

有了這個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> 

它不工作。但是當我在控制器中獲得與作用域的日期時,它就可以工作。 我認爲這是可能是因爲當我約會,我有良好的格式轉換它:

userRef.child(birthday).once('value', function(snap) { 

    $scope.birthday = new Date(snap.val()); 

    }) 

我怎樣才能得到正確的年齡?

謝謝。

+0

'user.more.birthday'看起來像什麼?拋出任何錯誤? – charlietfl

+0

像這樣:1992-05-07T22:00:00.000Z,我有任何錯誤...它只是當我想使用過濾器(或範圍),什麼也沒有發生...... – PositivProd

+1

創建演示在plunker或其他沙箱使用您的過濾器 – charlietfl

回答

0

多虧了PixelBits at this question給出的解決方案,我能解決我的問題。 這裏是我是如何進行的:

控制器:

$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) }} 

謝謝大家!

0

試試這個,在過濾字符串轉換日期時間像3號線

var jimApp = angular.module("mainApp", []); 
 

 
jimApp.controller('mainCtrl', function($scope){ 
 
    $scope.birthdate = "1992-05-07T22:00:00.000Z"; 
 
}); 
 

 
jimApp.filter('ageFilter', function() { 
 
    function calculateAge(birthday) { // birthday is a date 
 
     var ageDifMs = Date.now() - new Date(birthday).getTime(); 
 
     var ageDate = new Date(ageDifMs); // miliseconds from epoch 
 
     return Math.abs(ageDate.getUTCFullYear() - 1970); 
 
    } 
 

 
    return function(birthdate) { 
 
      return calculateAge(birthdate); 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="mainApp" ng-controller="mainCtrl"> 
 
    <div>{{birthdate | ageFilter}}</div> 
 
</div>

+0

你好,這個解決方案的工作原理,我用這個,當我想在控制器中檢索年齡的日期。 但我不想要這個,我想在ng-repeat中按日期檢索年齡。 – PositivProd