Merge pull request #22297 from civicrm/5.45
[civicrm-core.git] / ang / crmDialog.js
1 (function(angular, $, _) {
2 "use strict";
3
4 angular.module('crmDialog', CRM.angRequires('crmDialog'));
5
6 // Ex: <div crm-dialog="myDialogName"> ... <button ng-click="$dialog.cancel()">Cancel</button> ... </div>
7 // Ex: <div crm-dialog="myDialogName"> ... <button ng-click="$dialog.close(outputData)">Close</button> ... </div>
8 // Ex: <div crm-dialog="myDialogName"> ... <crm-dialog-button text="'Close'" on-click="$dialog.close()" /> ... </div>
9 angular.module('crmDialog').directive('crmDialog', function(dialogService) {
10 return {
11 restrict: 'A',
12 controllerAs: '$dialog',
13 controller: function($scope, $parse, $timeout) {
14 var $dialog = this;
15 $dialog.buttons = [];
16
17 $dialog.close = function (result) {
18 dialogService.close($dialog.name, result);
19 };
20
21 $dialog.cancel = function (result) {
22 dialogService.cancel($dialog.name);
23 };
24
25 $dialog.loadButtons = function() {
26 var buttons = [];
27 angular.forEach($dialog.buttons, function (crmDialogButton) {
28 var button = _.pick(crmDialogButton, ['id', 'icons', 'text']);
29 button.click = function () {
30 crmDialogButton.onClick();
31 };
32 buttons.push(button);
33 });
34 dialogService.setButtons($dialog.name, buttons);
35 $dialog.toggleButtons();
36 };
37
38 $dialog.toggleButtons = function() {
39 angular.forEach($dialog.buttons, function (crmDialogButton) {
40 $('#' + crmDialogButton.id).prop('disabled', crmDialogButton.disabled);
41 });
42 };
43
44 $timeout(function(){
45 $dialog.loadButtons();
46 $('.ui-dialog:last input:not([disabled]):not([type="submit"]):first').focus();
47 });
48
49 },
50 link: function(scope, element, attrs, controller) {
51 controller.name = attrs.crmDialog;
52 scope[attrs.crmDialog] = controller;
53 }
54 };
55 });
56
57 var idNum = 1;
58
59 // Ex: <crm-dialog-button text="ts('Do it')" icons="{primary: 'fa-foo'}" on-click="doIt()" />
60 angular.module('crmDialog').component('crmDialogButton', {
61 bindings: {
62 disabled: '<',
63 icons: '<',
64 text: '<',
65 onClick: '&'
66 },
67 require: {
68 crmDialog: '?^^crmDialog'
69 },
70 controller: function($scope) {
71 var $ctrl = this;
72 $ctrl.$onInit = function() {
73 $ctrl.crmDialog.buttons.push(this);
74 };
75 $ctrl.id = 'crmDialogButton_' + (idNum++);
76
77 $scope.$watch('$ctrl.disabled', function() {
78 $ctrl.crmDialog.toggleButtons();
79 });
80 }
81 });
82
83 })(angular, CRM.$, CRM._);