Angularjs: 封装layDate指令

【摘要】由于业务需要,将bootstrap-datetimepicker改成了layDate. layDate是一个较成熟且便于操作的jQuery日期插件,支持同一个视图内范围选择。封装成一个指令在多处调用。

.directive('defLaydate', function() {
  return {
    require: '?ngModel',
    restrict: 'A',
    scope: {
      ngModel: '=',  
    },
    link: function(scope, element, attr, ngModel) {
      var _date = null,_config={};
      // 初始化参数(具体参数可以查看API:http://www.layui.com/doc/modules/laydate.html)
      _config = {
        lang: 'en',
        elem: element[0],
        btns:['confirm'],
        format: !!attr.format ? attr.format : 'yyyy-MM-dd',
        range: attr.range,
        done: function(value, date, endDate) {
          ngModel.$setViewValue(value);
        }
      };
      !!attr.typeDate && (_config.type = attr.typeDate);

      // 初始化
       _date = laydate.render(_config);
      // 模型值同步到视图上
      ngModel.$render = function() {
        element.val(ngModel.$viewValue || '');
      };
    }
  }
})

HTML:

<div class="form-group">
    <label>Time</label>
    <div class="input-group">
        <span class="input-group-addon"><i class="fa fa-calendar icon"></i></span>
        <input def-laydate range="~" class="form-control" type="text" ng-model="dateText"/>
    </div>
</div> 

结果如下:

 

原文地址:https://www.cnblogs.com/koto/p/8079433.html