Commit | Line | Data |
---|---|---|
b396fc59 TO |
1 | (function(angular, $, _) { |
2 | // Represent a datetime field as if it were a radio ('schedule.mode') and a datetime ('schedule.datetime'). | |
3 | // example: <div crm-mailing-radio-date="mySchedule" ng-model="mailing.scheduled_date">...</div> | |
4 | angular.module('crmMailing').directive('crmMailingRadioDate', function() { | |
5 | return { | |
6 | require: 'ngModel', | |
7 | link: function($scope, element, attrs, ngModel) { | |
8 | ||
9 | var schedule = $scope[attrs.crmMailingRadioDate] = { | |
10 | mode: 'now', | |
11 | datetime: '' | |
12 | }; | |
13 | ||
14 | ngModel.$render = function $render() { | |
15 | var sched = ngModel.$viewValue; | |
16 | if (!_.isEmpty(sched)) { | |
17 | schedule.mode = 'at'; | |
18 | schedule.datetime = sched; | |
19 | } | |
20 | else { | |
21 | schedule.mode = 'now'; | |
22 | schedule.datetime = ''; | |
23 | } | |
24 | }; | |
25 | ||
26 | var updateParent = (function() { | |
27 | switch (schedule.mode) { | |
28 | case 'now': | |
29 | ngModel.$setViewValue(null); | |
30 | schedule.datetime = ''; | |
31 | break; | |
32 | case 'at': | |
33 | schedule.datetime = schedule.datetime || '?'; | |
34 | ngModel.$setViewValue(schedule.datetime); | |
35 | break; | |
36 | default: | |
37 | throw 'Unrecognized schedule mode: ' + schedule.mode; | |
38 | } | |
39 | }); | |
40 | ||
41 | element | |
42 | // Open datepicker when clicking "At" radio | |
43 | .on('click', ':radio[value=at]', function() { | |
44 | $('.crm-form-date', element).focus(); | |
45 | }) | |
46 | // Reset mode if user entered an invalid date | |
47 | .on('change', '.crm-hidden-date', function(e, context) { | |
48 | if (context === 'userInput' && $(this).val() === '' && $(this).siblings('.crm-form-date').val().length) { | |
49 | schedule.mode = 'at'; | |
50 | schedule.datetime = '?'; | |
51 | } | |
52 | }); | |
53 | ||
54 | $scope.$watch(attrs.crmMailingRadioDate + '.mode', updateParent); | |
55 | $scope.$watch(attrs.crmMailingRadioDate + '.datetime', function(newValue, oldValue) { | |
56 | // automatically switch mode based on datetime entry | |
57 | if (typeof oldValue === 'undefined') { | |
58 | oldValue = ''; | |
59 | } | |
60 | if (typeof newValue === 'undefined') { | |
61 | newValue = ''; | |
62 | } | |
63 | if (oldValue !== newValue) { | |
64 | if (_.isEmpty(newValue)) { | |
65 | schedule.mode = 'now'; | |
66 | } | |
67 | else { | |
68 | schedule.mode = 'at'; | |
69 | } | |
70 | } | |
71 | updateParent(); | |
72 | }); | |
73 | } | |
74 | }; | |
75 | }); | |
76 | })(angular, CRM.$, CRM._); |