简体   繁体   中英

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

I'm using angular-ui datepicker and currently have the settings declared in a controller, eg:

$scope.date = new Date();

$scope.open = function($event) {
  $event.preventDefault();
  $event.stopPropagation();

  $scope.opened = true;
};

In order to be DRY, I want to declare this in one place, so that the datepicker can be used anywhere, without having to declare the settings each time.

I've tried putting them into a factory that would be injected into a controller, but with no success. I'm quite new to building factories/services.

I found this SO question that mentions declaring the settings under the config method, like this:

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

But this doesn't work for me for some reason.

How can I declare the datepicker settings in once place to be used globally, or for injection?

To declare datepicker in 'one place' for easy re-use, I built a factory for the data/config:

.factory('datepickerService', function() {

  var factory = {};

  factory.date = new Date();

  factory.open = function($event) {
    $event.preventDefault();
    $event.stopPropagation();
    this.opened = true;
  };

  return factory;

});

Then a datepicker controller that injects the datepickerService , hooking the $scope up with the factory config.

.controller('datepickerCtrl', function ($scope, datepickerService) {

  $scope.date = datepickerService.date;
  $scope.open = datepickerService.open;

});

A directive:

.directive('supermanDatepicker', function () {

  return {
    templateUrl:'views/partials/datepicker.html'
  };

});

HTML partial template with the standard ui-boostrap datepicker (but declaring the controller)

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

Then finally, it can be plugged into any view:

<div superman-datepicker></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM