How to set default date in datetimepicker with ngmodel?

喜欢而已 提交于 2019-12-22 13:51:59

问题


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'
    };
  }
])

回答1:


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



来源:https://stackoverflow.com/questions/32588024/how-to-set-default-date-in-datetimepicker-with-ngmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!