crmMailing2 - Convert controller EditScheduleCtrl to directive crmMailingRadioDate
[civicrm-core.git] / js / angular-crmMailing2-directives.js
index cd11e3e30ead72ccbe020dcf6c95719cac168b77..4f79ab75a8cd4177f4723e1d1bb92b635891a568 100644 (file)
     };
   });
 
+  // Represent a datetime field as if it were a radio ('schedule.mode') and a datetime ('schedule.datetime').
+  // example: <div crm-mailing-radio-date="mySchedule" crm-model="mailing.scheduled_date">...</div>
+  // FIXME: use ngModel instead of adhoc crmModel
+  crmMailing2.directive('crmMailingRadioDate', function ($parse) {
+    return {
+      link: function ($scope, element, attrs) {
+        var schedModel = $parse(attrs.crmModel);
+
+        var schedule = $scope[attrs.crmMailingRadioDate] = {
+          mode: 'now',
+          datetime: ''
+        };
+        var updateChildren = (function () {
+          var sched = schedModel($scope);
+          if (sched) {
+            schedule.mode = 'at';
+            schedule.datetime = sched;
+          }
+          else {
+            schedule.mode = 'now';
+          }
+        });
+        var updateParent = (function () {
+          switch (schedule.mode) {
+            case 'now':
+              schedModel.assign($scope, null);
+              break;
+            case 'at':
+              schedModel.assign($scope, schedule.datetime);
+              break;
+            default:
+              throw 'Unrecognized schedule mode: ' + schedule.mode;
+          }
+        });
+
+        $scope.$watch(attrs.crmModel, updateChildren);
+        $scope.$watch(attrs.crmMailingRadioDate + '.mode', updateParent);
+        $scope.$watch(attrs.crmMailingRadioDate + '.datetime', function (newValue, oldValue) {
+          // automatically switch mode based on datetime entry
+          if (oldValue != newValue) {
+            if (!newValue || newValue == " ") {
+              schedule.mode = 'now';
+            }
+            else {
+              schedule.mode = 'at';
+            }
+          }
+          updateParent();
+        });
+      }
+    };
+  });
+
   crmMailing2.directive('crmMailingReviewBool', function () {
     return {
       scope: {