Bhavan Kumar Natarajan
Bhavan Kumar Natarajan

Reputation: 367

How to change UI Bootstrap Datepicker from controller to directive

I want to use UI bootstrap datepicker to all my pages. So it will not fall under any controller. I need it on directive format. My Angular code is

app.controller('DummyCtrl',['$scope', function($scope){
    $scope.datePicker = (function () {
    var method = {};
    method.instances = [];

    method.open = function ($event, instance) {
        $event.preventDefault();
        $event.stopPropagation();

        method.instances[instance] = true;
    };

    method.options = {
        'show-weeks': false,
        startingDay: 0
    };

    var formats = ['MM/dd/yyyy', 'dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
    method.format = formats[3];

    return method;
    }());


}]);

My Markup is

<div class="filtertab_title">
                 <span class="fil_datelabel">From</span>
                 <p class="input-group filter_datefield_wrap">
                    <input type="text" class="form-control filter_datefield" ng-model="dateFrom" datepicker-popup="{{datePicker.format}}" datepicker-options="datePicker.options" is-open="datePicker.instances['dateFrom']" close-text="Close" />
                    <span class="input-group-btn">
                        <button type="button" class="btn btn-default calendar_hit" ng-click="datePicker.open($event, 'dateFrom')"><i class="glyphicon glyphicon-calendar"></i></button>
                    </span>
                </p>
                </div>

Upvotes: 2

Views: 96

Answers (2)

Hulke
Hulke

Reputation: 857

Edited

Try this:

  YourApp.directive('datePicker', function () {

var controller = [
/* Your controller */
],

  template =  /* Your Template */;

  return {
      restrict: 'EA', //Default in 1.3+
      scope: {
          datasource: '=',
          add: '&',
      },
      controller: controller,
      template: template
  };
});

Hope it works for you. For more debugging please provide a fiddle..

Upvotes: 0

bipin52165
bipin52165

Reputation: 168

try this:

app.directive("uiDatepicker", function() {
  return {
    restrict: "A",
    require: "ngModel",
    link: function(scope, el, attr, ngModel) {
      return el.datepicker({
        dateFormat: attr.dateFormat,
        onSelect: function(dateText) {
          return scope.$apply(function() {
            return ngModel.$setViewValue(dateText);
          });
        }
      });
    }
  };
})

Upvotes: 1

Related Questions