如何使用Angularjs中的momentjs获取一周内的下一天和前几天

时间:2016-01-19 11:07:26

标签: angularjs momentjs

以下角度代码显示当周的日期:

function TodoCtrl($scope) {

  var currentDate = moment();
  var weekStart = currentDate.clone().startOf('week');
  var weekEnd = currentDate.clone().endOf('week');

  var days = [];
  for (i = 0; i <= 6; i++) {
    days.push(moment(weekStart).add(i, 'days').format("MMMM Do,dddd"));
  };
  $scope.weekDays = days;
}

和html:

<div ng-app>
  <div ng-controller="TodoCtrl">
    <div ng-repeat="day in weekDays">
      {{day}}
    </div>
  </div>
</div>

输出是:

  • 1月24日,星期日
  • 1月25日星期一
  • 1月26日,星期二
  • 1月27日,星期三
  • 1月28日,星期四
  • 1月29日,星期五
  • 1月30日星期六

我想要的是下一个和上一个按钮。当我点击下一个按钮时,将显示下周的日期。当我点击上一个按钮时,将显示前一周的日期。

请帮帮我。

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

function TodoCtrl($scope) {
  var currentDate = moment();

  $scope.calculateWeekDay = function() {
    var weekStart = currentDate.clone().startOf('week');
    var weekEnd = currentDate.clone().endOf('week');

    var days = [];
    for (i = 0; i <= 6; i++) {
      days.push(moment(weekStart).add(i, 'days').format("MMMM Do,dddd"));
    };

    $scope.weekDays = days;
  }

  $scope.onNextWeekClicked = function() {
    currentDate = currentDate.add(1, week);
    $scope.calculateWeekDay();
  }

  $scope.onPreviousWeekClicked = function() {
    currentDate = currentDate.subtract(1, week);
    $scope.calculateWeekDay();
  }
}

HTML:

<div ng-app>
  <div ng-controller="TodoCtrl">
    <div ng-repeat="day in weekDays">
      {{day}}
    </div>

    <button ng-click="onNextWeekClicked()">Next week</button>
    <button ng-click="onPreviousWeekClicked()">Previous week</button>
  </div>
</div>

答案 1 :(得分:1)

下面的内容对您有用。

function TodoCtrl($scope) {
    var currentDate = moment();
    
     var fnWeekDays = function(dt) {

        var currentDate = dt;
        var weekStart = currentDate.clone().startOf('week');
        var weekEnd = currentDate.clone().endOf('week');

        var days = [];
        for (i = 0; i <= 6; i++) {

            days.push(moment(weekStart).add(i, 'days').format("MMMM Do,dddd"));

        };
        return days;
    }
    
    $scope.weekDays = fnWeekDays(currentDate);
    $scope.nextWeek = function(dt) {
        $scope.weekDays = fnWeekDays(moment(dt, "MMMM Do,dddd").add(1, 'days'));
    };
    $scope.previousWeek = function(dt) {
        $scope.weekDays = fnWeekDays(moment(dt, "MMMM Do,dddd").subtract(1, 'days'));
    };

   
}
.done-true {
  text-decoration: line-through;
  color: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="TodoCtrl">
  <a ng-click="previousWeek(weekDays[0])">Previous</a>
  <a ng-click="nextWeek(weekDays[6])">Next</a>
    <div ng-repeat="day in weekDays">
      {{day}}
    </div>
  </div>
</div>

同样的JSFiddle