仿Angular Bootstrap TimePicker创建分钟数-秒数的输入控件


Posted in Javascript onJuly 01, 2016

在一个项目中需要一个用来输入分钟数和秒数的控件,然而调查了一些开源项目后并未发现合适的控件。在Angular Bootstrap UI中有一个类似的控件TimePicker,但是它并没有深入到分钟和秒的精度。
因此,决定参考它的源码然后自己进行实现。 
最终的效果如下:

 仿Angular Bootstrap TimePicker创建分钟数-秒数的输入控件

首先是该directive的定义:

app.directive('minuteSecondPicker', function() {
 return {
 restrict: 'EA',
 require: ['minuteSecondPicker', '?^ngModel'],
 controller: 'minuteSecondPickerController',
 replace: true,
 scope: {
  validity: '='
 },
 templateUrl: 'partials/directives/minuteSecondPicker.html',
 link: function(scope, element, attrs, ctrls) {
  var minuteSecondPickerCtrl = ctrls[0],
  ngModelCtrl = ctrls[1];

  if(ngModelCtrl) {
  minuteSecondPickerCtrl.init(ngModelCtrl, element.find('input'));
  }
 }
 };
});

在以上的link函数中,ctrls是一个数组: ctrls[0]是定义在本directive上的controller实例,ctrls[1]是ngModelCtrl,即ng-model对应的controller实例。这个顺序实际上是通过require: ['minuteSecondPicker', '?^ngModel']定义的。
注意到第一个依赖就是directive本身的名字,此时会将该directive中controller声明的对应实例传入。第二个依赖的写法有些奇怪:"?^ngModel",?的含义是即使没有找到该依赖,也不要抛出异常,即该依赖是一个可选项。^的含义是查找父元素的controller。
然后,定义该directive中用到的一些默认设置,通过constant directive实现:

app.constant('minuteSecondPickerConfig', {
 minuteStep: 1,
 secondStep: 1,
 readonlyInput: false,
 mousewheel: true
});

紧接着是directive对应的controller,它的声明如下:

app.controller('minuteSecondPickerController', ['$scope', '$attrs', '$parse', 'minuteSecondPickerConfig', 
 function($scope, $attrs, $parse, minuteSecondPickerConfig) {
 ...
}]);

在directive的link函数中,调用了此controller的init方法:

this.init = function(ngModelCtrl_, inputs) {
 ngModelCtrl = ngModelCtrl_;
 ngModelCtrl.$render = this.render;

 var minutesInputEl = inputs.eq(0),
  secondsInputEl = inputs.eq(1);

 var mousewheel = angular.isDefined($attrs.mousewheel) ? 
  $scope.$parent.$eval($attrs.mousewheel) : minuteSecondPickerConfig.mousewheel;
 if(mousewheel) {
  this.setupMousewheelEvents(minutesInputEl, secondsInputEl);
 }

 $scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ?
  $scope.$parent.$eval($attrs.readonlyInput) : minuteSecondPickerConfig.readonlyInput;
 this.setupInputEvents(minutesInputEl, secondsInputEl);
 };

init方法接受的第二个参数是inputs,在link函数中传入的是:element.find('input')。 所以第一个输入框用来输入分钟,第二个输入框用来输入秒。
然后,检查是否覆盖了mousewheel属性,如果没有覆盖则使用在constant中设置的默认mousewheel,并进行相关设置如下:

// respond on mousewheel spin
 this.setupMousewheelEvents = function(minutesInputEl, secondsInputEl) {
 var isScrollingUp = function(e) {
  if(e.originalEvent) {
  e = e.originalEvent;
  }

  // pick correct delta variable depending on event
  var delta = (e.wheelData) ? e.wheelData : -e.deltaY;
  return (e.detail || delta > 0);
 };

 minutesInputEl.bind('mousewheel wheel', function(e) {
  $scope.$apply((isScrollingUp(e)) ? $scope.incrementMinutes() : $scope.decrementMinutes());
  e.preventDefault();
 });

 secondsInputEl.bind('mousewheel wheel', function(e) {
  $scope.$apply((isScrollingUp(e)) ? $scope.incrementSeconds() : $scope.decrementSeconds());
  e.preventDefault();
 });
 };

init方法最后会对inputs本身进行一些设置: 

// respond on direct input
 this.setupInputEvents = function(minutesInputEl, secondsInputEl) {
 if($scope.readonlyInput) {
  $scope.updateMinutes = angular.noop;
  $scope.updateSeconds = angular.noop;
  return;
 }

 var invalidate = function(invalidMinutes, invalidSeconds) {
  ngModelCtrl.$setViewValue(null);
  ngModelCtrl.$setValidity('time', false);
  $scope.validity = false;
  if(angular.isDefined(invalidMinutes)) {
  $scope.invalidMinutes = invalidMinutes;
  }
  if(angular.isDefined(invalidSeconds)) {
  $scope.invalidSeconds = invalidSeconds;
  }
 };

 $scope.updateMinutes = function() {
  var minutes = getMinutesFromTemplate();

  if(angular.isDefined(minutes)) {
  selected.minutes = minutes;
  refresh('m');
  } else {
  invalidate(true);
  }
 };

 minutesInputEl.bind('blur', function(e) {
  if(!$scope.invalidMinutes && $scope.minutes < 10) {
  $scope.$apply(function() {
   $scope.minutes = pad($scope.minutes);
  });
  }
 });

 $scope.updateSeconds = function() {
  var seconds = getSecondsFromTemplate();

  if(angular.isDefined(seconds)) {
  selected.seconds = seconds;
  refresh('s');
  } else {
  invalidate(undefined, true);
  }
 };

 secondsInputEl.bind('blur', function(e) {
  if(!$scope.invalidSeconds && $scope.seconds < 10) {
  $scope.$apply(function() {
   $scope.seconds = pad($scope.seconds);
  });
  }
 });
 };

此方法中,声明了用于设置输入非法的invalidate函数,它会在scope中暴露一个validity = false属性让页面有机会做出合适的反应。
 如果用户使用了一个变量来表示minuteStep或者secondStep,那么还需要设置相应的watchers:

var minuteStep = minuteSecondPickerConfig.minuteStep;
 if($attrs.minuteStep) {
 $scope.parent.$watch($parse($attrs.minuteStep), function(value) {
  minuteStep = parseInt(value, 10);
 });
 }

 var secondStep = minuteSecondPickerConfig.secondStep;
 if($attrs.secondStep) {
 $scope.parent.$watch($parse($attrs.secondStep), function(value) {
  secondStep = parseInt(value, 10);
 });
 }

完整的directive实现代码如下:

var app = angular.module("minuteSecondPickerDemo");

app.directive('minuteSecondPicker', function() {
 return {
 restrict: 'EA',
 require: ['minuteSecondPicker', '?^ngModel'],
 controller: 'minuteSecondPickerController',
 replace: true,
 scope: {
  validity: '='
 },
 templateUrl: 'partials/directives/minuteSecondPicker.html',
 link: function(scope, element, attrs, ctrls) {
  var minuteSecondPickerCtrl = ctrls[0],
  ngModelCtrl = ctrls[1];

  if(ngModelCtrl) {
  minuteSecondPickerCtrl.init(ngModelCtrl, element.find('input'));
  }
 }
 };
});

app.constant('minuteSecondPickerConfig', {
 minuteStep: 1,
 secondStep: 1,
 readonlyInput: false,
 mousewheel: true
});

app.controller('minuteSecondPickerController', ['$scope', '$attrs', '$parse', 'minuteSecondPickerConfig', 
 function($scope, $attrs, $parse, minuteSecondPickerConfig) {

 var selected = {
  minutes: 0,
  seconds: 0
 },
 ngModelCtrl = {
  $setViewValue: angular.noop
 };

 this.init = function(ngModelCtrl_, inputs) {
 ngModelCtrl = ngModelCtrl_;
 ngModelCtrl.$render = this.render;

 var minutesInputEl = inputs.eq(0),
  secondsInputEl = inputs.eq(1);

 var mousewheel = angular.isDefined($attrs.mousewheel) ? 
  $scope.$parent.$eval($attrs.mousewheel) : minuteSecondPickerConfig.mousewheel;
 if(mousewheel) {
  this.setupMousewheelEvents(minutesInputEl, secondsInputEl);
 }

 $scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ?
  $scope.$parent.$eval($attrs.readonlyInput) : minuteSecondPickerConfig.readonlyInput;
 this.setupInputEvents(minutesInputEl, secondsInputEl);
 };

 var minuteStep = minuteSecondPickerConfig.minuteStep;
 if($attrs.minuteStep) {
 $scope.parent.$watch($parse($attrs.minuteStep), function(value) {
  minuteStep = parseInt(value, 10);
 });
 }

 var secondStep = minuteSecondPickerConfig.secondStep;
 if($attrs.secondStep) {
 $scope.parent.$watch($parse($attrs.secondStep), function(value) {
  secondStep = parseInt(value, 10);
 });
 }

 // respond on mousewheel spin
 this.setupMousewheelEvents = function(minutesInputEl, secondsInputEl) {
 var isScrollingUp = function(e) {
  if(e.originalEvent) {
  e = e.originalEvent;
  }

  // pick correct delta variable depending on event
  var delta = (e.wheelData) ? e.wheelData : -e.deltaY;
  return (e.detail || delta > 0);
 };

 minutesInputEl.bind('mousewheel wheel', function(e) {
  $scope.$apply((isScrollingUp(e)) ? $scope.incrementMinutes() : $scope.decrementMinutes());
  e.preventDefault();
 });

 secondsInputEl.bind('mousewheel wheel', function(e) {
  $scope.$apply((isScrollingUp(e)) ? $scope.incrementSeconds() : $scope.decrementSeconds());
  e.preventDefault();
 });
 };

 // respond on direct input
 this.setupInputEvents = function(minutesInputEl, secondsInputEl) {
 if($scope.readonlyInput) {
  $scope.updateMinutes = angular.noop;
  $scope.updateSeconds = angular.noop;
  return;
 }

 var invalidate = function(invalidMinutes, invalidSeconds) {
  ngModelCtrl.$setViewValue(null);
  ngModelCtrl.$setValidity('time', false);
  $scope.validity = false;
  if(angular.isDefined(invalidMinutes)) {
  $scope.invalidMinutes = invalidMinutes;
  }
  if(angular.isDefined(invalidSeconds)) {
  $scope.invalidSeconds = invalidSeconds;
  }
 };

 $scope.updateMinutes = function() {
  var minutes = getMinutesFromTemplate();

  if(angular.isDefined(minutes)) {
  selected.minutes = minutes;
  refresh('m');
  } else {
  invalidate(true);
  }
 };

 minutesInputEl.bind('blur', function(e) {
  if(!$scope.invalidMinutes && $scope.minutes < 10) {
  $scope.$apply(function() {
   $scope.minutes = pad($scope.minutes);
  });
  }
 });

 $scope.updateSeconds = function() {
  var seconds = getSecondsFromTemplate();

  if(angular.isDefined(seconds)) {
  selected.seconds = seconds;
  refresh('s');
  } else {
  invalidate(undefined, true);
  }
 };

 secondsInputEl.bind('blur', function(e) {
  if(!$scope.invalidSeconds && $scope.seconds < 10) {
  $scope.$apply(function() {
   $scope.seconds = pad($scope.seconds);
  });
  }
 });
 };

 this.render = function() {
 var time = ngModelCtrl.$modelValue ? {
  minutes: ngModelCtrl.$modelValue.minutes,
  seconds: ngModelCtrl.$modelValue.seconds
 } : null;

 // adjust the time for invalid value at first time
 if(time.minutes < 0) {
  time.minutes = 0;
 }
 if(time.seconds < 0) {
  time.seconds = 0;
 }

 var totalSeconds = time.minutes * 60 + time.seconds;
 time = {
  minutes: Math.floor(totalSeconds / 60),
  seconds: totalSeconds % 60
 };

 if(time) {
  selected = time;
  makeValid();
  updateTemplate();
 }
 };

 // call internally when the model is valid
 function refresh(keyboardChange) {
 makeValid();
 ngModelCtrl.$setViewValue({
  minutes: selected.minutes,
  seconds: selected.seconds
 });
 updateTemplate(keyboardChange);
 }

 function makeValid() {
 ngModelCtrl.$setValidity('time', true);
 $scope.validity = true;
 $scope.invalidMinutes = false;
 $scope.invalidSeconds = false;
 }

 function updateTemplate(keyboardChange) {
 var minutes = selected.minutes,
  seconds = selected.seconds;

 $scope.minutes = keyboardChange === 'm' ? minutes : pad(minutes);
 $scope.seconds = keyboardChange === 's' ? seconds : pad(seconds);
 }

 function pad(value) {
 return ( angular.isDefined(value) && value.toString().length < 2 ) ? '0' + value : value;
 }

 function getMinutesFromTemplate() {
 var minutes = parseInt($scope.minutes, 10);
 return (minutes >= 0) ? minutes : undefined;
 }

 function getSecondsFromTemplate() {
 var seconds = parseInt($scope.seconds, 10);
 if(seconds >= 60) {
  seconds = 59;
 }

 return (seconds >= 0) ? seconds : undefined;
 }

 $scope.incrementMinutes = function() {
 addSeconds(minuteStep * 60);
 };

 $scope.decrementMinutes = function() {
 addSeconds(-minuteStep * 60);
 };

 $scope.incrementSeconds = function() {
 addSeconds(secondStep);
 };

 $scope.decrementSeconds = function() {
 addSeconds(-secondStep);
 };

 function addSeconds(seconds) {
 var newSeconds = selected.minutes * 60 + selected.seconds + seconds;
 if(newSeconds < 0) {
  newSeconds = 0;
 }

 selected = {
  minutes: Math.floor(newSeconds / 60),
  seconds: newSeconds % 60
 };

 refresh();
 }

 $scope.previewTime = function(minutes, seconds) {
 var totalSeconds = parseInt(minutes, 10) * 60 + parseInt(seconds, 10),
  hh = pad(Math.floor(totalSeconds / 3600)),
  mm = pad(minutes % 60),
  ss = pad(seconds);

 return hh + ':' + mm + ':' + ss;
 };
}]);

对应的Template实现: 

<table>
 <tbody>
 <tr class="text-center">
  <td>
  <a ng-click="incrementMinutes()" class="btn btn-link">
   <span class="glyphicon glyphicon-chevron-up"></span>
  </a>
  </td>
  <td> </td>
  <td>
  <a ng-click="incrementSeconds()" class="btn btn-link">
   <span class="glyphicon glyphicon-chevron-up"></span>
  </a>
  </td>
  <td> </td>
 </tr>
 <tr>
  <td style="width:50px;" class="form-group" ng-class="{'has-error': invalidMinutes}">
  <input type="text" ng-model="minutes" ng-change="updateMinutes()" class="form-control text-center" ng-mousewheel="incrementMinutes()" ng-readonly="readonlyInput" maxlength="3">
  </td>
  <td>:</td>
  <td style="width:50px;" class="form-group" ng-class="{'has-error': invalidSeconds}">
  <input type="text" ng-model="seconds" ng-change="updateSeconds()" class="form-control text-center" ng-mousewheel="incrementSeconds()" ng-readonly="readonlyInput" maxlength="2">
  <td>
  <!-- preview column -->
  <td>
  <span class="label label-primary" ng-show="validity">
   {{ previewTime(minutes, seconds) }}
  </span>
  </td>
 </tr>
 <tr class="text-center">
  <td>
  <a ng-click="decrementMinutes()" class="btn btn-link">
   <span class="glyphicon glyphicon-chevron-down"></span>
  </a>
  </td>
  <td> </td>
  <td>
  <a ng-click="decrementSeconds()" class="btn btn-link">
   <span class="glyphicon glyphicon-chevron-down"></span>
  </a>
  </td>
  <td> </td>
 </tr>
 </tbody>
</table>

测试代码(即前面截图dialog的源代码):

<div class="modal-header">
 <h3 class="modal-title">Highlight on <span class="label label-primary">{{ movieName }}</span></h3>
</div>
<div class="modal-body">

 <div class="row">
 <div id="highlight-start" class="col-xs-6">
  <h4>Start Time:</h4>
  <minute-second-picker ng-model="startTime" validity="startTimeValidity"></minute-second-picker>
 </div>

 <div id="highlight-end" class="col-xs-6">
  <h4>End Time:</h4>
  <minute-second-picker ng-model="endTime" validity="endTimeValidity"></minute-second-picker>
 </div>
 </div>
 <div class="row">
 <div class="col-xs-2">
  Tags:
 </div>
 <div class="col-xs-10">
  <tags model="tags" src="s as s.name for s in sourceTags" options="{ addable: 'true' }"></tags>
 </div>
 </div>
</div>
<div class="modal-footer">
 <button class="btn btn-primary" ng-click="ok()" ng-disabled="!startTimeValidity || !endTimeValidity || durationIncorrect(endTime, startTime)">OK</button>
 <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>

如果大家还想深入学习,可以点击这里进行学习,再为大家附3个精彩的专题:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
JavaScript 中的事件教程
Apr 05 Javascript
鼠标滑上去后图片放大浮出效果的js代码
May 28 Javascript
JQuery实现简单验证码提示解决方案
Dec 20 Javascript
jquery div拖动效果示例代码
Dec 08 Javascript
js根据日期判断星座的示例代码
Jan 23 Javascript
利用jQuery实现WordPress中@的ID悬浮显示评论内容
Dec 11 Javascript
使用Sticky组件实现带sticky效果的tab导航和滚动导航的方法
Mar 22 Javascript
jQuery实现ajax的叠加和停止(终止ajax请求)
Aug 08 Javascript
浅谈Vue.js之初始化el以及数据的绑定说明
Nov 14 Javascript
Node.js中出现未捕获异常的处理方法
Jun 29 Javascript
基于Vue+Webpack拆分路由文件实现管理
Nov 16 Javascript
浅谈TypeScript 索引签名的理解
Oct 16 Javascript
精彩的Bootstrap案例分享 重点在注释!(选项卡、栅格布局)
Jul 01 #Javascript
很棒的Bootstrap选项卡切换效果
Jul 01 #Javascript
AngularJS优雅的自定义指令
Jul 01 #Javascript
如何解决手机浏览器页面点击不跳转浏览器双击放大网页
Jul 01 #Javascript
再谈Javascript中的基本类型和引用类型(推荐)
Jul 01 #Javascript
JavaScript中有关一个数组中最大值和最小值及它们的下表的输出的解决办法
Jul 01 #Javascript
Bootstrap编写一个兼容主流浏览器的受众门户式风格页面
Jul 01 #Javascript
You might like
探讨:如何使用PHP实现计算两个日期间隔的年、月、周、日数
2013/06/13 PHP
php用户注册时常用的检验函数实例总结
2014/12/22 PHP
CentOS安装php v8js教程
2015/02/26 PHP
php中Snoopy类用法实例
2015/06/19 PHP
jQuery链使用指南
2015/01/20 Javascript
jQuery调取jSon数据并展示的方法
2015/01/29 Javascript
弹出遮罩层后禁止滚动效果【实现代码】
2016/04/29 Javascript
浅谈jQuery animate easing的具体使用方法(推荐)
2016/06/17 Javascript
AngularJS指令与控制器之间的交互功能示例
2016/12/14 Javascript
微信小程序实战之自定义抽屉菜单(7)
2017/04/18 Javascript
详解从新建vue项目到引入组件Element的方法
2017/08/29 Javascript
Nodejs调用WebService的示例代码
2017/09/29 NodeJs
vue编译打包本地查看index文件的方法
2018/02/23 Javascript
详解使用 Node.js 开发简单的脚手架工具
2018/06/08 Javascript
js使用ajax传值给后台,后台返回字符串处理方法
2018/08/08 Javascript
详解webpack打包后如何调试的方法步骤
2018/11/07 Javascript
JS简单数组排序操作示例【sort方法】
2019/05/17 Javascript
Vue拖拽组件列表实现动态页面配置功能
2019/06/17 Javascript
浅谈小程序globalData的那些事儿
2019/11/01 Javascript
Vue实现 点击显示再点击隐藏效果(点击页面空白区域也隐藏效果)
2020/01/16 Javascript
vue微信分享插件使用方法详解
2020/02/18 Javascript
vue和小程序项目中使用iconfont的方法
2020/05/19 Javascript
详解React 元素渲染
2020/07/07 Javascript
JS实现简易图片自动轮播
2020/10/16 Javascript
[06:10]6.81新信使新套装!给你一个炫酷的DOTA2
2014/05/06 DOTA
[51:53]完美世界DOTA2联赛决赛日 Inki vs LBZS 第二场 11.08
2020/11/10 DOTA
python类:class创建、数据方法属性及访问控制详解
2016/07/25 Python
Python编程django实现同一个ip十分钟内只能注册一次
2017/11/03 Python
对python list 遍历删除的正确方法详解
2018/06/29 Python
浅析python的Lambda表达式
2019/02/27 Python
keras绘制acc和loss曲线图实例
2020/06/15 Python
HTML5 使用 sessionStorage 进行页面传值的方法
2018/07/02 HTML / CSS
反腐倡廉警示教育活动总结
2014/05/05 职场文书
2014年扫黄打非工作总结
2014/12/03 职场文书
祝福语集锦:给妹妹结婚的祝福语
2019/12/18 职场文书
Python字典和列表性能之间的比较
2021/06/07 Python