2016-12-17 84 views
0

我是Angularjs的新手,如何在我的日历中添加开放式焦点实现(类似于Microsoft Windows 7日历),如下所示,我们使用的是Angular材质版本1.0.1。我们决定不更新我们的Angular材料到1.1.1。如何在Angularjs日历中实现'Open on focus'和'monthpicker'?

<!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

创建一个名为同现有的日期选择器指令指令。这样您就不必向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

+0

感谢您试用它,你提到工作不正常演示。打开焦点(通过点击日历)必须工作。 – user7303839

+0

@ user7303839对我来说工作得很好。你正在测试哪个浏览器? – tasseKATT

+0

我们在chrome 54.0.2840.100中试过它,IE11能纠正它并指出正确的解决方案吗? – user7303839