Edward Tanguay
Edward Tanguay

Reputation: 193282

How to set default date in datetimepicker with ngmodel?

I've created this angular directive that wraps a jQuery plugin datetimepicker.

How can I get the default dates defined in the controller to display as the default date in the controls?

http://jsfiddle.net/edwardtanguay/ef1o3c95/5

I've tried a number of variations with ngModel.$viewValue but can't get the yyyy-mm-dd text to simply display in the control.

<div ng-controller="mainController">

    <div class="form-group">
        <div class='input-group date' timepicker ng-model="date1">
            <input type='text' class="form-control" />
            <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>
        </div>
        <div>{{date1 | date:'yyyy-MM-dd HH:mm'}}</div>  
    </div>

    <div class="form-group">
        <div class='input-group date' timepicker ng-model="date2">
            <input type='text' class="form-control" />
            <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>
        </div>
        <div>{{date2 | date:'yyyy-MM-dd HH:mm'}}</div>
    </div>

</div>

angular.module('myApp', [])
.controller('mainController', function($scope) {
    $scope.date1 = '2015-09-01 00:00';
    $scope.date2 = '2015-09-30 23:59';
})
.directive('timepicker', [

  function() {
    var link;
    link = function(scope, element, attr, ngModel) {
        console.log(ngModel);
        element = $(element);
        element.datetimepicker({
            format: 'YYYY-MM-DD HH:mm',
            defaultDate: ngModel.$viewValue
        });
        element.on('dp.change', function(event) {
            scope.$apply(function() {
                ngModel.$setViewValue(event.date._d);
            });
        });
    };

    return {
      restrict: 'A',
      link: link,
      require: 'ngModel'
    };
  }
])

Upvotes: 3

Views: 10605

Answers (1)

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

I think you can use isolated scope directive here, and expose the ngModel directive value to the timepicker directive scope as below.

return {
  restrict: 'A',
  scope: {
    date: '=ngModel'
  },
  link: link
};

element.datetimepicker({
   format: 'YYYY-MM-DD HH:mm',
   defaultDate: scope.date
});

here each and every directive instance it has unique scope and that scope is sharing the ngModel directive value as scope.date. and no need of require property.

here is the DEMO

here is the Directive DOC and see the Isolating the Scope of a Directive section for more info.

here is a good article.


And note that you can also use the shared scope directive as like your one as below.

element.datetimepicker({
   format: 'YYYY-MM-DD HH:mm',
   defaultDate: scope[attr.ngModel]
});

here is the DEMO

Upvotes: 5

Related Questions