input_date.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. ///<reference path="../../../headers/common.d.ts" />
  2. import moment from 'moment';
  3. import * as dateMath from 'app/core/utils/datemath';
  4. export function inputDateDirective() {
  5. return {
  6. restrict: 'A',
  7. require: 'ngModel',
  8. link: function ($scope, $elem, attrs, ngModel) {
  9. var format = 'YYYY-MM-DD HH:mm:ss';
  10. var fromUser = function (text) {
  11. if (text.indexOf('now') !== -1) {
  12. if (!dateMath.isValid(text)) {
  13. ngModel.$setValidity("error", false);
  14. return undefined;
  15. }
  16. ngModel.$setValidity("error", true);
  17. return text;
  18. }
  19. var parsed;
  20. if ($scope.ctrl.isUtc) {
  21. parsed = moment.utc(text, format);
  22. } else {
  23. parsed = moment(text, format);
  24. }
  25. if (!parsed.isValid()) {
  26. ngModel.$setValidity("error", false);
  27. return undefined;
  28. }
  29. ngModel.$setValidity("error", true);
  30. return parsed;
  31. };
  32. var toUser = function (currentValue) {
  33. if (moment.isMoment(currentValue)) {
  34. return currentValue.format(format);
  35. } else {
  36. return currentValue;
  37. }
  38. };
  39. ngModel.$parsers.push(fromUser);
  40. ngModel.$formatters.push(toUser);
  41. }
  42. };
  43. }