ng_model_on_blur.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { rangeUtil } from '@grafana/data';
  2. import coreModule from './core_module';
  3. function ngModelOnBlur() {
  4. return {
  5. restrict: 'A',
  6. priority: 1,
  7. require: 'ngModel',
  8. link: (scope: any, elm: any, attr: any, ngModelCtrl: any) => {
  9. if (attr.type === 'radio' || attr.type === 'checkbox') {
  10. return;
  11. }
  12. elm.off('input keydown change');
  13. elm.bind('blur', () => {
  14. scope.$apply(() => {
  15. ngModelCtrl.$setViewValue(elm.val());
  16. });
  17. });
  18. },
  19. };
  20. }
  21. function emptyToNull() {
  22. return {
  23. restrict: 'A',
  24. require: 'ngModel',
  25. link: (scope: any, elm: any, attrs: any, ctrl: any) => {
  26. ctrl.$parsers.push((viewValue: any) => {
  27. if (viewValue === '') {
  28. return null;
  29. }
  30. return viewValue;
  31. });
  32. },
  33. };
  34. }
  35. function validTimeSpan() {
  36. return {
  37. require: 'ngModel',
  38. link: (scope: any, elm: any, attrs: any, ctrl: any) => {
  39. ctrl.$validators.integer = (modelValue: any, viewValue: any) => {
  40. if (ctrl.$isEmpty(modelValue)) {
  41. return true;
  42. }
  43. if (viewValue.indexOf('$') === 0 || viewValue.indexOf('+$') === 0) {
  44. return true; // allow template variable
  45. }
  46. const info = rangeUtil.describeTextRange(viewValue);
  47. return info.invalid !== true;
  48. };
  49. },
  50. };
  51. }
  52. coreModule.directive('ngModelOnblur', ngModelOnBlur);
  53. coreModule.directive('emptyToNull', emptyToNull);
  54. coreModule.directive('validTimeSpan', validTimeSpan);