如何在一个地方声明angular ui引导程序日期选择器设置

How can angular ui-bootstrap datepicker settings be declared in one place?

本文关键字:ui angular 声明 日期 设置 选择器 引导程序 一个 方声明      更新时间:2023-09-26

我使用的是angular ui日期选择器,目前在控制器中声明了设置,例如:

$scope.date = new Date();
$scope.open = function($event) {
  $event.preventDefault();
  $event.stopPropagation();
  $scope.opened = true;
};

为了DRY,我想在一个地方声明它,这样日期选择器就可以在任何地方使用,而不必每次都声明设置。

我试过把它们放进一个工厂,然后注入控制器,但没有成功。我对建造工厂/服务业很陌生。

我发现了这个SO问题,其中提到在config方法下声明设置,如下所示:

.config(['datepickerConfig', function(datepickerConfig) {
  datepickerConfig.showWeeks = false;
}]);

但出于某种原因,这对我不起作用。

如何一次性声明日期选择器设置以全局使用或用于注入?

为了在"一个地方"声明日期选择器以便于重用,我为data/config:建立了一个工厂

.factory('datepickerService', function() {
  var factory = {};
  factory.date = new Date();
  factory.open = function($event) {
    $event.preventDefault();
    $event.stopPropagation();
    this.opened = true;
  };
  return factory;
});

然后是一个日期选择器控制器,它注入datepickerService,将$scope与工厂配置挂钩。

.controller('datepickerCtrl', function ($scope, datepickerService) {
  $scope.date = datepickerService.date;
  $scope.open = datepickerService.open;
});

A指令:

.directive('supermanDatepicker', function () {
  return {
    templateUrl:'views/partials/datepicker.html'
  };
});

带有标准ui boostrap日期选择器的HTML部分模板(但声明控制器)

<div class="input-group" ng-controller="datepickerCtrl">
  <input type="text" 
         class="form-control" 
         datepicker-popup="{{format}}" 
         ng-model="shortDate"
         placeholder="dd-mm-yyyy" 
         is-open="opened" 
         min-date="minDate" 
         datepicker-options="dateOptions" 
         date-disabled="disabled(date, mode)" 
         ng-required="true" 
         close-text="Close" />
  <span class="input-group-btn">
    <button type="button" 
            class="btn" 
            ng-click="open($event)">
              <i class="glyphicon glyphicon-calendar"></i>
    </button>
  </span>
</div>

最后,它可以插入任何视图:

<div superman-datepicker></div>