使用angularjs和UI bootstrap创建时间范围UI

时间:2015-01-21 14:07:31

标签: angularjs twitter-bootstrap datepicker timepicker

我使用了一个日期选择器和两个时间戳来创建给定日期内的时间范围(产生两个日期对象)。

datepicker的ng-model指向开始日期,并将日期部分复制到ng-change上的结束日期。到目前为止一切都很好。

但是:修改结束时间会将结束日期恢复为原始值!

标记:

<!doctype html>
<html ng-app="ui.bootstrap.demo">
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>
    <script src="example.js"></script>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>

<div ng-controller="TimepickerDemoCtrl">
  <h1>Purpose: UI for a time range within a day</h1>
  <p>Issue: Updating the date sets the correct end date BUT updating the end time reverts the end date back to its original value.</p>
  <div class="input-group" style="width:150px">
      <input type="text" required ng-model="item.startDate" ng-change="setEndDate()" class="form-control" datepicker-popup="yyyy-MM-dd" is-open="datePicker" />
      <span class="input-group-btn">
          <button type="button" class="btn btn-default" ng-click="openPicker($event, 'datePicker')"><i class="glyphicon glyphicon-calendar"></i></button>
      </span>
  </div>
  <timepicker ng-model="item.startDate" show-meridian="false"></timepicker>
  <timepicker ng-model="item.endDate" show-meridian="false"></timepicker>

  <pre class="alert alert-info">start is: {{item.startDate | date:'yyyy-MM-dd HH:mm' }}<br/>end is:   {{item.endDate | date:'yyyy-MM-dd HH:mm' }}<br/>Duration: {{item.duration() | number:2}}</pre>

</div>
  </body>
</html>

脚本:

angular.module('ui.bootstrap.demo', ['ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('TimepickerDemoCtrl', function ($scope, $log) {
  var starttime = new Date();
  starttime.setHours(8);
  starttime.setMinutes(0);
  var endtime = new Date();
  endtime.setHours(17);
  endtime.setMinutes(0);

  $scope.item = {
    startDate: starttime,
    endDate: endtime,
    duration: function () { return moment.duration(moment(this.endDate) - moment(this.startDate)).asHours() }
  }

  $scope.setEndDate = function() {
    $scope.item.endDate.setDate($scope.item.startDate.getDate());
    $scope.item.endDate.setMonth($scope.item.startDate.getMonth());
    $scope.item.endDate.setFullYear($scope.item.startDate.getFullYear());
  }

  $scope.openPicker = function ($event, pickerInstance) {
    $event.preventDefault();
    $event.stopPropagation();
    $scope[pickerInstance] = true;
  };

});

http://plnkr.co/edit/zCFgf0mt4WOZeG9MPA9d

1 个答案:

答案 0 :(得分:0)

在某些原因,UI Bootstrap datepicker不会在您的情况下观察endDate值修改。

您可以复制startDate对象并链接到endDate:

,而不是修改endDate
  $scope.setEndDate = function() {
    $scope.item.endDate = angular.copy($scope.item.startDate);
  };