如何在Angularjs日历中实现“Open on focus”和“monthpicker”?

时间:2016-12-17 20:32:48

标签: angularjs angularjs-directive angularjs-scope

我是Angularjs的新手,我如何在我的日历中添加开放焦点实现(类似于Microsoft Windows 7日历),如下所示我们使用Angular材料版本1.0.1。我们决定不将Angular材料更新为1.1.1。

<!doctype html>
<html ng-app="datepickerBasicUsage">

<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.0.1/angular-material.css">
</head>

<body>

  <div ng-controller="AppCtrl" style='padding: 40px;'>
    <md-content>
      <md-datepicker ng-model="birthdate" placeholder="Enter date" md-max-date="maxDate" ng-focus="open()"></md-datepicker>
    </md-content>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-animate.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-aria.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-material/1.0.1/angular-material.js"></script>
  <script src="app.js"></script>

</body>

</html>

app.js ---

angular.module('datepickerBasicUsage', ['ngMaterial'])
  .controller('AppCtrl', function($scope, $timeout) {
    $scope.birthdate = new Date();

    $scope.maxDate = new Date(
      $scope.birthdate.getFullYear(),
      $scope.birthdate.getMonth(),
      $scope.birthdate.getDate());

    $scope.open = function() {
      $timeout(function() {
        $scope.birthdate = new Date();
        $scope.maxDate = new Date(
          $scope.birthdate.getFullYear(),
          $scope.birthdate.getMonth(),
          $scope.birthdate.getDate());
      }, 400);
    }
  });          

1 个答案:

答案 0 :(得分:1)

创建一个与现有datepicker指令相同的指令。这样您就不必向HTML中添加任何内容,因为您已经在使用md-datepicker

app.directive('mdDatepicker', function() {

  return {
    link: function(scope, element) {

      var controller = element.controller('mdDatepicker');

      var event = {
        target: document.body
      };

      var input = element.find('input');

      input.on('focus', function(e) {

        scope.$apply(function() {
          controller.openCalendarPane(event);
        });
      });

      input.on('click', function(e) {

        e.stopPropagation();
      });
    }
  };
});

该指令检索正常mdDatepicker指令使用的控制器,并在输入聚焦时调用openCalendarPane方法。

需要假事件对象,因为mdDatepicker在内部使用event.target知道在关闭日期选择器时要将焦点设置为什么。

需要点击监听器和event.stopPropagation才能在Firefox中运行(至少在我测试过的版本中),或者如果通过单击输入内部打开日历,它将立即再次关闭。

演示: http://plnkr.co/edit/YdtVwa3MnTyrl5wS1eZ8?p=preview