-4

我正在嘗試編寫簡單的ng-repeat,顯示過去12個月的列表,從今天開始。Angular將顯示過去12個月的日期

因此,舉例來說,如果我加載我今天申請(2014年5月),我將有一個列表:

May 2014 
Apr 2014 
Mar 2014 
Feb 2014 
Jan 2014 
Dec 2013 
Nov 2013 
Oct 2013 
Sep 2013 
Aug 2013 
Jul 2013 
Jun 2013 

如果我是來查看比方說,2014年9月,則列表會顯示爲:

Sep 2014 
Aug 2014 
Jul 2014 
Jun 2014 
May 2014 
Apr 2014 
Mar 2014 
Feb 2014 
Jan 2014 
Dec 2013 
Nov 2013 
Oct 2013 

HTML:

<div ng-app=""> 
    <div ng-controller="Ctrl"> 
    <li ng-repeat="currMonth in months">{{currMonth}}</li> 
    </div> 
</div> 

JS:

function Ctrl($scope) { 
    $scope.months = [ 
     "01 - Jan", 
     "02 - Feb", 
     "03 - Mar", 
     "04 - Apr", 
     "05 - May", 
     "06 - Jun", 
     "07 - Jul", 
     "08 - Aug", 
     "09 - Sep", 
     "10 - Oct", 
     "11 - Nov", 
     "12 - Dec" 
    ]; 
    $scope.month = 'null'; 
} 
+1

您是否嘗試過自己做的邏輯是什麼? – JoseM

回答

3

該邏輯相當簡單,並且與angularjs沒有任何關係。這就是說,我想爲自己嘗試一下,這就是我想出來的。

angular.module('test', []).controller('Ctrl', function($scope) { 
    var date = new Date(); 
    var months = [], 
     monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", 
         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; 
    for(var i = 0; i < 12; i++) { 
     months.push(monthNames[date.getMonth()] + ' ' + date.getFullYear()); 

     // Subtract a month each time 
     date.setMonth(date.getMonth() - 1); 
    } 
    $scope.months = months; 
}); 

這是我用來創建它的jsfiddle

+0

感謝這是我以後的事情。我更願意保持我的控制器非常簡單,可以按照以下內容將其放入函數中:http://jsfiddle.net/oampz/Z6MLQ/1/ –

+0

或通過調用像下面這樣的指令:http://jsfiddle.net/oampz/xCLN7/1 / –

0

由於我們使用的角度,利用在$過濾指令

angular.module('test', []).controller('Ctrl', function($scope, $filter) { 
 
    
 
    $scope.premonths = 12; 
 
    
 
    $scope.getMonths = function(){ 
 
     $scope.months = []; 
 
     var today = new Date(); 
 
     var endDate = new Date() 
 
     endDate.setMonth(endDate.getMonth() - $scope.premonths) 
 

 
     for(var d=today;d > endDate;d.setMonth(d.getMonth() - 1)) { 
 
    $scope.months.push({month:($filter('date')(d, 'MMMM')),year:$filter('date')(d,  'yyyy')}) 
 
    } 
 
    
 
    } 
 

 
    $scope.getMonths(); 
 
});
input { 
 
display:inline-block; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<html ng-app='test'> 
 
<body ng-controller='Ctrl'> 
 
    Get last <input ng-model='premonths' ng-change='getMonths()'> months 
 
    <ul> 
 
    <li ng-repeat='month in months'> 
 
    {{month.month}} - {{ month.year}} 
 
    </li> 
 
    </ul> 
 
</body> 
 
</html>

相關問題