-4

我正在尝试编写简单的 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';
}
4

2 回答 2

4

逻辑相当简单,实际上与 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 。

于 2014-05-20T16:49:37.250 回答
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();
});
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>

于 2017-01-09T01:07:06.807 回答