wui-date 本身只支持接收和返回日期格式的字符串,导致在实际项目中使用太过于麻烦,还需要前后台进行字符串日期转换,特此进行了修改,将wui-date的显示值和真实值进行了区分,保证显示值为【字符串】而真实值为【日期类型】,这样大大提高了可可用度!
注意:部分js方法是本人项目里的,应用到自己项目时将对应js方法替换掉即可!
接下来直接给大家奉送上改动源码的代码块,如有不足欢迎前端大牛提供建议:
第一步:将wui-date的html模版 fieldTemplate方法第三行html字符的ng-model='ngModel' 改为 ng-model="showNgModel" ,当然showNgModel 这个可以自定义,大家按照自己命名习惯来修改就可以,参考如下标红部分:
'<input class="wui-input wui-input-block wui-date-input" type="text" placeholder="{{placeholder}}" ng-model="showNgModel" autocomplete="off" ng-blur=checkDateFormat()>'
第二步:监听 fieldLink 方法中添加 监听真实值变化的逻辑【这里真实值就是表单中绑定的date变量】
//监听真实值变化,赋值给显示值 scope.$watch("ngModel",function(newV,oldV){ if(!isEmpty(newV) && newV instanceof Date){ scope.showNgModel=newV.format(scope.format); }else{ scope.showNgModel=newV; } });第三步:修改输出时间 outputDate 方法 【作用:在日期控件选择完日期后,将真实值和显示值进行赋值和转换】
// 输出时间 function outputDate() { if(scope.ngModel == null || scope.ngModel instanceof Date){ scope.ngModel = GMTDate; scope.showNgModel =GMTDate.format(scope.format); }else{ scope.ngModel = dateFormat(GMTToStrDate(GMTDate)); scope.showNgModel = GMTDate.format(scope.format); } }第四步:openPicker,dateInit 两个方法中 GMTDateInit方法参数改为:scope.showNgModel
第五步:修改 checkDateFormat 方法【作用:当焦点离开日期输入框时触发,主要解决手动输入日期后的问题】
//焦点离开日期输入框触发:将手动输入的显示值转换为真实值 scope.checkDateFormat = function() { if(isEmpty(scope.showNgModel)){ scope.ngModel=null; }else{ var sta_str = (scope.showNgModel).replace(/-/g,"/"); var newDate = new Date(sta_str); //输入的显示值格式正确则直接赋值 if(!isNaN(newDate)){ scope.ngModel = newDate; } //输入的显示值错误则将之前的真实值赋值给显示值 else{ scope.showNgModel = dateFormat(scope.ngModel); } } }第六步【重】:wui-date.js中所有日期格式中月份格式为mm 改为MM ,小时:hh 改为 HH 并去掉初始化时的格式化 toLowerCase() 方法 【源码中因为这个月份为mm 和小时 hh 会造成格式化出来的值是不对的这个地方务必要注意改过来!】