我正在尝试编写简单的ng-repeat,显示过去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';
}
答案 0 :(得分: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。
答案 1 :(得分:0)
由于我们使用angular,因此利用$ filter指令
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();
});
&#13;
input {
display:inline-block;
}
&#13;
<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>
&#13;