crmDialog - Dynamically update button text & icons, apply callbacks within scope
authorColeman Watts <coleman@civicrm.org>
Fri, 4 Feb 2022 04:18:41 +0000 (23:18 -0500)
committerColeman Watts <coleman@civicrm.org>
Fri, 4 Feb 2022 04:18:41 +0000 (23:18 -0500)
Before: Only "disabled" property of button was watched and kept in-sync,
button callback was applied outside of Angular digest cycle.

After: Title and icons also kept in-sync,
button callback applied within Angular digest cycle.

ang/crmDialog.js

index 0fb189225c7b5679df065b91bf006234082ddc7b..3da59e82cd96b0d1af5b040a12d8fc17ae9ea3d5 100644 (file)
         var $dialog = this;
         $dialog.buttons = [];
 
-        $dialog.close = function (result) {
+        $dialog.close = function(result) {
           dialogService.close($dialog.name, result);
         };
 
-        $dialog.cancel = function (result) {
+        $dialog.cancel = function() {
           dialogService.cancel($dialog.name);
         };
 
         $dialog.loadButtons = function() {
           var buttons = [];
           angular.forEach($dialog.buttons, function (crmDialogButton) {
-            var button = _.pick(crmDialogButton, ['id', 'icons', 'text']);
-            button.click = function () {
-              crmDialogButton.onClick();
+            var button = _.pick(crmDialogButton, ['icons', 'text', 'disabled']);
+            button.click = function() {
+              $scope.$apply(crmDialogButton.onClick);
             };
             buttons.push(button);
           });
           dialogService.setButtons($dialog.name, buttons);
-          $dialog.toggleButtons();
         };
 
-        $dialog.toggleButtons = function() {
-          angular.forEach($dialog.buttons, function (crmDialogButton) {
-            $('#' + crmDialogButton.id).prop('disabled', crmDialogButton.disabled);
-          });
-        };
-
-        $timeout(function(){
-          $dialog.loadButtons();
+        $timeout(function() {
           $('.ui-dialog:last input:not([disabled]):not([type="submit"]):first').focus();
         });
 
@@ -80,8 +72,6 @@
     };
   });
 
-  var idNum = 1;
-
   // Ex: <crm-dialog-button text="ts('Do it')" icons="{primary: 'fa-foo'}" on-click="doIt()" />
   angular.module('crmDialog').component('crmDialogButton', {
     bindings: {
       var $ctrl = this;
       $ctrl.$onInit = function() {
         $ctrl.crmDialog.buttons.push(this);
+        $scope.$watch('$ctrl.disabled', $ctrl.crmDialog.loadButtons);
+        $scope.$watch('$ctrl.text', $ctrl.crmDialog.loadButtons);
+        $scope.$watch('$ctrl.icons', $ctrl.crmDialog.loadButtons);
       };
-      $ctrl.id = 'crmDialogButton_' + (idNum++);
-
-      $scope.$watch('$ctrl.disabled', function() {
-        $ctrl.crmDialog.toggleButtons();
-      });
     }
   });