1 /// crmUi: Sundry UI helpers
2 (function (angular
, $, _
) {
6 documentTitle
= 'CiviCRM';
8 angular
.module('crmUi', CRM
.angRequires('crmUi'))
10 // example <div crm-ui-accordion crm-title="ts('My Title')" crm-collapsed="true">...content...</div>
11 // WISHLIST: crmCollapsed should support two-way/continuous binding
12 .directive('crmUiAccordion', function() {
17 template
: '<div ng-class="cssClasses"><div class="crm-accordion-header">{{crmUiAccordion.title}} <a crm-ui-help="help" ng-if="help"></a></div><div class="crm-accordion-body" ng-transclude></div></div>',
19 link: function (scope
, element
, attrs
) {
21 'crm-accordion-wrapper': true,
22 collapsed
: scope
.crmUiAccordion
.collapsed
25 scope
.$watch('crmUiAccordion', function(crmUiAccordion
) {
26 if (crmUiAccordion
&& crmUiAccordion
.help
) {
27 scope
.help
= crmUiAccordion
.help
.clone({}, {
28 title
: crmUiAccordion
.title
37 // crmUiAlert({text: 'My text', title: 'My title', type: 'error'});
38 // crmUiAlert({template: '<a ng-click="ok()">Hello</a>', scope: $scope.$new()});
39 // var h = crmUiAlert({templateUrl: '~/crmFoo/alert.html', scope: $scope.$new()});
41 .service('crmUiAlert', function($compile
, $rootScope
, $templateRequest
, $q
) {
43 return function crmUiAlert(params
) {
44 var id
= 'crmUiAlert_' + (++count
);
46 if (params
.templateUrl
) {
47 tpl
= $templateRequest(params
.templateUrl
);
49 else if (params
.template
) {
50 tpl
= params
.template
;
53 params
.text
= '<div id="' + id
+ '"></div>'; // temporary stub
55 var result
= CRM
.alert(params
.text
, params
.title
, params
.type
, params
.options
);
57 $q
.when(tpl
, function(html
) {
58 var scope
= params
.scope
|| $rootScope
.$new();
59 var linker
= $compile(html
);
60 $('#' + id
).append($(linker(scope
)));
67 // Simple wrapper around $.crmDatepicker.
68 // example with no time input: <input crm-ui-datepicker="{time: false}" ng-model="myobj.datefield"/>
69 // example with custom date format: <input crm-ui-datepicker="{date: 'm/d/y'}" ng-model="myobj.datefield"/>
70 .directive('crmUiDatepicker', function () {
77 link: function (scope
, element
, attrs
, ngModel
) {
78 ngModel
.$render = function () {
79 element
.val(ngModel
.$viewValue
).change();
83 .crmDatepicker(scope
.crmUiDatepicker
)
84 .on('change', function() {
85 var requiredLength
= 19;
86 if (scope
.crmUiDatepicker
&& scope
.crmUiDatepicker
.time
=== false) {
89 if (scope
.crmUiDatepicker
&& scope
.crmUiDatepicker
.date
=== false) {
92 ngModel
.$setValidity('incompleteDateTime', !($(this).val().length
&& $(this).val().length
!== requiredLength
));
98 // Display debug information (if available)
99 // For richer DX, checkout Batarang/ng-inspector (Chrome/Safari), or AngScope/ng-inspect (Firefox).
100 // example: <div crm-ui-debug="myobject" />
101 .directive('crmUiDebug', function ($location
) {
107 template: function() {
108 var args
= $location
.search();
109 if (args
&& args
.angularDebug
) {
110 var jsonTpl
= (CRM
.angular
.modules
.indexOf('jsonFormatter') < 0) ? '<pre>{{data|json}}</pre>' : '<json-formatter json="data" open="1"></json-formatter>';
111 return '<div crm-ui-accordion=\'{title: ts("Debug (%1)", {1: crmUiDebug}), collapsed: true}\'>' + jsonTpl
+ '</div>';
115 link: function(scope
, element
, attrs
) {
116 var args
= $location
.search();
117 if (args
&& args
.angularDebug
) {
118 scope
.ts
= CRM
.ts(null);
119 scope
.$parent
.$watch(attrs
.crmUiDebug
, function(data
) {
127 // Display a field/row in a field list
128 // example: <div crm-ui-field="{title: ts('My Field')}"> {{mydata}} </div>
129 // example: <div crm-ui-field="{name: 'subform.myfield', title: ts('My Field')}"> <input crm-ui-id="subform.myfield" name="myfield" /> </div>
130 // example: <div crm-ui-field="{name: 'subform.myfield', title: ts('My Field')}"> <input crm-ui-id="subform.myfield" name="myfield" required /> </div>
131 // example: <div crm-ui-field="{name: 'subform.myfield', title: ts('My Field'), help: hs('help_field_name'), required: true}"> {{mydata}} </div>
132 .directive('crmUiField', function() {
133 // Note: When writing new templates, the "label" position is particular. See/patch "var label" below.
135 default: '~/crmUi/field.html',
136 checkbox
: '~/crmUi/field-cb.html'
140 require
: '^crmUiIdScope',
143 // {title, name, help, helpFile}
146 templateUrl: function(tElement
, tAttrs
){
147 var layout
= tAttrs
.crmLayout
? tAttrs
.crmLayout
: 'default';
148 return templateUrls
[layout
];
151 link: function (scope
, element
, attrs
, crmUiIdCtrl
) {
152 $(element
).addClass('crm-section');
154 scope
.$watch('crmUiField', function(crmUiField
) {
155 if (crmUiField
&& crmUiField
.help
) {
156 scope
.help
= crmUiField
.help
.clone({}, {
157 title
: crmUiField
.title
165 // example: <div ng-form="subform" crm-ui-id-scope><label crm-ui-for="subform.foo">Foo:</label><input crm-ui-id="subform.foo" name="foo"/></div>
166 .directive('crmUiId', function () {
168 require
: '^crmUiIdScope',
171 pre: function (scope
, element
, attrs
, crmUiIdCtrl
) {
172 var id
= crmUiIdCtrl
.get(attrs
.crmUiId
);
173 element
.attr('id', id
);
179 // for example, see crmUiHelp
180 .service('crmUiHelp', function(){
181 // example: var h = new FieldHelp({id: 'foo'}); h.open();
182 function FieldHelp(options
) {
183 this.options
= options
;
185 angular
.extend(FieldHelp
.prototype, {
187 return this.options
[n
];
189 open
: function open() {
190 CRM
.help(this.options
.title
, {id
: this.options
.id
, file
: this.options
.file
});
192 clone
: function clone(options
, defaults
) {
193 return new FieldHelp(angular
.extend({}, defaults
, this.options
, options
));
197 // example: var hs = crmUiHelp({file: 'CRM/Foo/Bar'});
198 return function(defaults
){
199 // example: hs('myfield')
200 // example: hs({id: 'myfield', title: 'Foo Bar', file: 'Whiz/Bang'})
201 return function(options
) {
202 if (_
.isString(options
)) {
203 options
= {id
: options
};
205 return new FieldHelp(angular
.extend({}, defaults
, options
));
210 // Display a help icon
211 // Example: Use a default *.hlp file
212 // scope.hs = crmUiHelp({file: 'Path/To/Help/File'});
213 // HTML: <a crm-ui-help="hs({title:ts('My Field'), id:'my_field'})">
214 // Example: Use an explicit *.hlp file
215 // HTML: <a crm-ui-help="hs({title:ts('My Field'), id:'my_field', file:'CRM/Foo/Bar'})">
216 .directive('crmUiHelp', function() {
219 link: function(scope
, element
, attrs
) {
220 setTimeout(function() {
221 var crmUiHelp
= scope
.$eval(attrs
.crmUiHelp
);
222 var title
= crmUiHelp
&& crmUiHelp
.get('title') ? ts('%1 Help', {1: crmUiHelp
.get('title')}) : ts('Help');
223 element
.attr('title', title
);
227 .addClass('helpicon')
229 .on('click', function(e
) {
231 scope
.$eval(attrs
.crmUiHelp
).open();
237 // example: <div ng-form="subform" crm-ui-id-scope><label crm-ui-for="subform.foo">Foo:</label><input crm-ui-id="subform.foo" name="foo"/></div>
238 .directive('crmUiFor', function ($parse
, $timeout
) {
240 require
: '^crmUiIdScope',
242 template
: '<span ng-class="cssClasses"><span ng-transclude/><span crm-ui-visible="crmIsRequired" class="crm-marker" title="This field is required.">*</span></span>',
244 link: function (scope
, element
, attrs
, crmUiIdCtrl
) {
245 scope
.crmIsRequired
= false;
246 scope
.cssClasses
= {};
248 if (!attrs
.crmUiFor
) return;
250 var id
= crmUiIdCtrl
.get(attrs
.crmUiFor
);
251 element
.attr('for', id
);
254 var updateCss = function () {
255 scope
.cssClasses
['crm-error'] = !ngModel
.$valid
&& !ngModel
.$pristine
;
258 // Note: if target element is dynamically generated (eg via ngInclude), then it may not be available
259 // immediately for initialization. Use retries/retryDelay to initialize such elements.
260 var init = function (retries
, retryDelay
) {
261 var input
= $('#' + id
);
262 if (input
.length
=== 0 && !attrs
.crmUiForceRequired
) {
265 init(retries
-1, retryDelay
);
271 if (attrs
.crmUiForceRequired
) {
272 scope
.crmIsRequired
= true;
276 var tgtScope
= scope
;//.$parent;
277 if (attrs
.crmDepth
) {
278 for (var i
= attrs
.crmDepth
; i
> 0; i
--) {
279 tgtScope
= tgtScope
.$parent
;
283 if (input
.attr('ng-required')) {
284 scope
.crmIsRequired
= scope
.$parent
.$eval(input
.attr('ng-required'));
285 scope
.$parent
.$watch(input
.attr('ng-required'), function (isRequired
) {
286 scope
.crmIsRequired
= isRequired
;
290 scope
.crmIsRequired
= input
.prop('required');
293 ngModel
= $parse(attrs
.crmUiFor
)(tgtScope
);
295 ngModel
.$viewChangeListeners
.push(updateCss
);
306 // Define a scope in which a name like "subform.foo" maps to a unique ID.
307 // example: <div ng-form="subform" crm-ui-id-scope><label crm-ui-for="subform.foo">Foo:</label><input crm-ui-id="subform.foo" name="foo"/></div>
308 .directive('crmUiIdScope', function () {
312 controllerAs
: 'crmUiIdCtrl',
313 controller: function($scope
) {
315 this.get = function(name
) {
317 ids
[name
] = "crmUiId_" + (++uidCount
);
322 link: function (scope
, element
, attrs
) {}
326 // Display an HTML blurb inside an IFRAME.
327 // example: <iframe crm-ui-iframe="getHtmlContent()"></iframe>
328 // example: <iframe crm-ui-iframe crm-ui-iframe-src="getUrl()"></iframe>
329 .directive('crmUiIframe', function ($parse
) {
332 crmUiIframeSrc
: '@', // expression which evaluates to a URL
333 crmUiIframe
: '@' // expression which evaluates to HTML content
335 link: function (scope
, elm
, attrs
) {
336 var iframe
= $(elm
)[0];
337 iframe
.setAttribute('width', '100%');
338 iframe
.setAttribute('height', '250px');
339 iframe
.setAttribute('frameborder', '0');
341 var refresh = function () {
342 if (attrs
.crmUiIframeSrc
) {
343 iframe
.setAttribute('src', scope
.$parent
.$eval(attrs
.crmUiIframeSrc
));
346 var iframeHtml
= scope
.$parent
.$eval(attrs
.crmUiIframe
);
348 var doc
= iframe
.document
;
349 if (iframe
.contentDocument
) {
350 doc
= iframe
.contentDocument
;
352 else if (iframe
.contentWindow
) {
353 doc
= iframe
.contentWindow
.document
;
357 doc
.writeln(iframeHtml
);
362 // If the iframe is in a dialog, respond to resize events
363 $(elm
).parent().on('dialogresize dialogopen', function(e
, ui
) {
364 $(this).css({padding
: '0', margin
: '0', overflow
: 'hidden'});
365 iframe
.setAttribute('height', '' + $(this).innerHeight() + 'px');
368 $(elm
).parent().on('dialogresize', function(e
, ui
) {
369 iframe
.setAttribute('class', 'resized');
372 scope
.$parent
.$watch(attrs
.crmUiIframe
, refresh
);
378 // <a ng-click="$broadcast('my-insert-target', 'some new text')>Insert</a>
379 // <textarea crm-ui-insert-rx='my-insert-target'></textarea>
380 .directive('crmUiInsertRx', function() {
382 link: function(scope
, element
, attrs
) {
383 scope
.$on(attrs
.crmUiInsertRx
, function(e
, tokenName
) {
384 CRM
.wysiwyg
.insert(element
, tokenName
);
385 $(element
).select2('close').select2('val', '');
386 CRM
.wysiwyg
.focus(element
);
392 // Define a rich text editor.
393 // example: <textarea crm-ui-id="myForm.body_html" crm-ui-richtext name="body_html" ng-model="mailing.body_html"></textarea>
394 .directive('crmUiRichtext', function ($timeout
) {
397 link: function (scope
, elm
, attr
, ngModel
) {
399 var editor
= CRM
.wysiwyg
.create(elm
);
405 $(elm
).on('blur', function() {
406 $timeout(function() {
407 scope
.$eval(attr
.ngBlur
);
412 ngModel
.$render = function(value
) {
413 editor
.done(function() {
414 CRM
.wysiwyg
.setVal(elm
, ngModel
.$viewValue
|| '');
421 // Display a lock icon (based on a boolean).
422 // example: <a crm-ui-lock binding="mymodel.boolfield"></a>
423 // example: <a crm-ui-lock
424 // binding="mymodel.boolfield"
425 // title-locked="ts('Boolfield is locked')"
426 // title-unlocked="ts('Boolfield is unlocked')"></a>
427 .directive('crmUiLock', function ($parse
, $rootScope
) {
428 var defaultVal = function (defaultValue
) {
429 var f = function (scope
) {
432 f
.assign = function (scope
, value
) {
438 // like $parse, but accepts a defaultValue in case expr is undefined
439 var parse = function (expr
, defaultValue
) {
440 return expr
? $parse(expr
) : defaultVal(defaultValue
);
445 link: function (scope
, element
, attrs
) {
446 var binding
= parse(attrs
.binding
, true);
447 var titleLocked
= parse(attrs
.titleLocked
, ts('Locked'));
448 var titleUnlocked
= parse(attrs
.titleUnlocked
, ts('Unlocked'));
450 $(element
).addClass('crm-i lock-button');
451 var refresh = function () {
452 var locked
= binding(scope
);
455 .removeClass('fa-unlock')
457 .prop('title', titleLocked(scope
))
462 .removeClass('fa-lock')
463 .addClass('fa-unlock')
464 .prop('title', titleUnlocked(scope
))
469 $(element
).click(function () {
470 binding
.assign(scope
, !binding(scope
));
472 $rootScope
.$digest();
475 scope
.$watch(attrs
.binding
, refresh
);
476 scope
.$watch(attrs
.titleLocked
, refresh
);
477 scope
.$watch(attrs
.titleUnlocked
, refresh
);
484 // CrmUiOrderCtrl is a controller class which manages sort orderings.
486 // JS: $scope.myOrder = new CrmUiOrderCtrl(['+field1', '-field2]);
487 // $scope.myOrder.toggle('field1');
488 // $scope.myOrder.setDir('field2', '');
489 // HTML: <tr ng-repeat="... | order:myOrder.get()">...</tr>
490 .service('CrmUiOrderCtrl', function(){
491 function CrmUiOrderCtrl(defaults
){
492 this.values
= defaults
;
494 angular
.extend(CrmUiOrderCtrl
.prototype, {
495 get: function get() {
498 getDir
: function getDir(name
) {
499 if (this.values
.indexOf(name
) >= 0 || this.values
.indexOf('+' + name
) >= 0) {
502 if (this.values
.indexOf('-' + name
) >= 0) {
507 // @return bool TRUE if something is removed
508 remove
: function remove(name
) {
509 var idx
= this.values
.indexOf(name
);
511 this.values
.splice(idx
, 1);
518 setDir
: function setDir(name
, dir
) {
519 return this.toggle(name
, dir
);
521 // Toggle sort order on a field.
522 // To set a specific order, pass optional parameter 'next' ('+', '-', or '').
523 toggle
: function toggle(name
, next
) {
524 if (!next
&& next
!== '') {
526 if (this.remove(name
) || this.remove('+' + name
)) {
529 if (this.remove('-' + name
)) {
535 this.values
.unshift('+' + name
);
537 else if (next
== '-') {
538 this.values
.unshift('-' + name
);
542 return CrmUiOrderCtrl
;
545 // Define a controller which manages sort order. You may interact with the controller
546 // directly ("myOrder.toggle('fieldname')") order using the helper, crm-ui-order-by.
548 // <span crm-ui-order="{var: 'myOrder', defaults: {'-myField'}}"></span>
549 // <th><a crm-ui-order-by="[myOrder,'myField']">My Field</a></th>
550 // <tr ng-repeat="... | order:myOrder.get()">...</tr>
551 // <button ng-click="myOrder.toggle('myField')">
552 .directive('crmUiOrder', function(CrmUiOrderCtrl
) {
554 link: function(scope
, element
, attrs
){
555 var options
= angular
.extend({var: 'crmUiOrderBy'}, scope
.$eval(attrs
.crmUiOrder
));
556 scope
[options
.var] = new CrmUiOrderCtrl(options
.defaults
);
561 // For usage, see crmUiOrder (above)
562 .directive('crmUiOrderBy', function() {
564 link: function(scope
, element
, attrs
) {
565 function updateClass(crmUiOrderCtrl
, name
) {
566 var dir
= crmUiOrderCtrl
.getDir(name
);
568 .toggleClass('sorting_asc', dir
=== '+')
569 .toggleClass('sorting_desc', dir
=== '-')
570 .toggleClass('sorting', dir
=== '');
573 element
.on('click', function(e
){
574 var tgt
= scope
.$eval(attrs
.crmUiOrderBy
);
575 tgt
[0].toggle(tgt
[1]);
576 updateClass(tgt
[0], tgt
[1]);
581 var tgt
= scope
.$eval(attrs
.crmUiOrderBy
);
582 updateClass(tgt
[0], tgt
[1]);
587 // Display a fancy SELECT (based on select2).
588 // usage: <select crm-ui-select="{placeholder:'Something',allowClear:true,...}" ng-model="myobj.field"><option...></select>
589 .directive('crmUiSelect', function ($parse
, $timeout
) {
596 link: function (scope
, element
, attrs
, ngModel
) {
597 // In cases where UI initiates update, there may be an extra
598 // call to refreshUI, but it doesn't create a cycle.
601 ngModel
.$render = function () {
602 $timeout(function () {
603 // ex: msg_template_id adds new item then selects it; use $timeout to ensure that
604 // new item is added before selection is made
605 var newVal
= _
.cloneDeep(ngModel
.$modelValue
);
606 // Fix possible data-type mismatch
607 if (typeof newVal
=== 'string' && element
.select2('container').hasClass('select2-container-multi')) {
608 newVal
= newVal
.length
? newVal
.split(',') : [];
610 element
.select2('val', newVal
);
614 function refreshModel() {
615 var oldValue
= ngModel
.$viewValue
, newValue
= element
.select2('val');
616 if (oldValue
!= newValue
) {
617 scope
.$parent
.$apply(function () {
618 ngModel
.$setViewValue(newValue
);
624 // TODO watch select2-options
625 element
.crmSelect2(scope
.crmUiSelect
|| {});
627 element
.on('change', refreshModel
);
636 // Render a crmEntityRef widget
637 // usage: <input crm-entityref="{entity: 'Contact', select: {allowClear:true}}" ng-model="myobj.field" />
638 .directive('crmEntityref', function ($parse
, $timeout
) {
644 link: function (scope
, element
, attrs
, ngModel
) {
645 // In cases where UI initiates update, there may be an extra
646 // call to refreshUI, but it doesn't create a cycle.
648 ngModel
.$render = function () {
649 $timeout(function () {
650 // ex: msg_template_id adds new item then selects it; use $timeout to ensure that
651 // new item is added before selection is made
652 var newVal
= _
.cloneDeep(ngModel
.$modelValue
);
653 // Fix possible data-type mismatch
654 if (typeof newVal
=== 'string' && element
.select2('container').hasClass('select2-container-multi')) {
655 newVal
= newVal
.length
? newVal
.split(',') : [];
657 element
.select2('val', newVal
);
660 function refreshModel() {
661 var oldValue
= ngModel
.$viewValue
, newValue
= element
.select2('val');
662 if (oldValue
!= newValue
) {
663 scope
.$parent
.$apply(function () {
664 ngModel
.$setViewValue(newValue
);
670 // TODO can we infer "entity" from model?
671 element
.crmEntityRef(scope
.crmEntityref
|| {});
672 element
.on('change', refreshModel
);
673 $timeout(ngModel
.$render
);
681 // validate multiple email text
682 // usage: <input crm-multiple-email type="text" ng-model="myobj.field" />
683 .directive('crmMultipleEmail', function ($parse
, $timeout
) {
686 link: function(scope
, element
, attrs
, ctrl
) {
687 ctrl
.$parsers
.unshift(function(viewValue
) {
688 // if empty value provided simply bypass validation
689 if (_
.isEmpty(viewValue
)) {
690 ctrl
.$setValidity('crmMultipleEmail', true);
694 // split email string on basis of comma
695 var emails
= viewValue
.split(',');
696 // regex pattern for single email
697 var emailRegex
= /\S+@\S+\.\S+/;
699 var validityArr
= emails
.map(function(str
){
700 return emailRegex
.test(str
.trim());
703 if ($.inArray(false, validityArr
) > -1) {
704 ctrl
.$setValidity('crmMultipleEmail', false);
706 ctrl
.$setValidity('crmMultipleEmail', true);
713 // example <div crm-ui-tab id="tab-1" crm-title="ts('My Title')" count="3">...content...</div>
714 // WISHLIST: use a full Angular component instead of an incomplete jQuery wrapper
715 .directive('crmUiTab', function($parse
) {
717 require
: '^crmUiTabSet',
725 template
: '<div ng-transclude></div>',
727 link: function (scope
, element
, attrs
, crmUiTabSetCtrl
) {
728 crmUiTabSetCtrl
.add(scope
);
733 // example: <div crm-ui-tab-set><div crm-ui-tab crm-title="Tab 1">...</div><div crm-ui-tab crm-title="Tab 2">...</div></div>
734 .directive('crmUiTabSet', function() {
741 templateUrl
: '~/crmUi/tabset.html',
743 controllerAs
: 'crmUiTabSetCtrl',
744 controller: function($scope
, $parse
) {
745 var tabs
= $scope
.tabs
= []; // array<$scope>
746 this.add = function(tab
) {
747 if (!tab
.id
) throw "Tab is missing 'id'";
751 link: function (scope
, element
, attrs
) {}
755 // Generic, field-independent form validator.
756 // example: <span ng-model="placeholder" crm-ui-validate="foo && bar || whiz" />
757 // example: <span ng-model="placeholder" crm-ui-validate="foo && bar || whiz" crm-ui-validate-name="myError" />
758 .directive('crmUiValidate', function() {
762 link: function(scope
, element
, attrs
, ngModel
) {
763 var validationKey
= attrs
.crmUiValidateName
? attrs
.crmUiValidateName
: 'crmUiValidate';
764 scope
.$watch(attrs
.crmUiValidate
, function(newValue
){
765 ngModel
.$setValidity(validationKey
, !!newValue
);
771 // like ng-show, but hides/displays elements using "visibility" which maintains positioning
772 // example <div crm-ui-visible="false">...content...</div>
773 .directive('crmUiVisible', function($parse
) {
779 link: function (scope
, element
, attrs
) {
780 var model
= $parse(attrs
.crmUiVisible
);
781 function updatecChildren() {
782 element
.css('visibility', model(scope
.$parent
) ? 'inherit' : 'hidden');
785 scope
.$parent
.$watch(attrs
.crmUiVisible
, updatecChildren
);
790 // example: <div crm-ui-wizard="myWizardCtrl"><div crm-ui-wizard-step crm-title="ts('Step 1')">...</div><div crm-ui-wizard-step crm-title="ts('Step 2')">...</div></div>
791 // example with custom nav classes: <div crm-ui-wizard crm-ui-wizard-nav-class="ng-animate-out ...">...</div>
792 // Note: "myWizardCtrl" has various actions/properties like next() and $first().
793 // WISHLIST: Allow each step to determine if it is "complete" / "valid" / "selectable"
794 // WISHLIST: Allow each step to enable/disable (show/hide) itself
795 .directive('crmUiWizard', function() {
800 crmUiWizardNavClass
: '@' // string, A list of classes that will be added to the nav items
802 templateUrl
: '~/crmUi/wizard.html',
804 controllerAs
: 'crmUiWizardCtrl',
805 controller: function($scope
, $parse
) {
806 var steps
= $scope
.steps
= []; // array<$scope>
807 var crmUiWizardCtrl
= this;
809 var selectedIndex
= null;
811 var findIndex = function() {
813 angular
.forEach(steps
, function(step
, stepKey
) {
814 if (step
.selected
) found
= stepKey
;
819 /// @return int the index of the current step
820 this.$index = function() { return selectedIndex
; };
821 /// @return bool whether the currentstep is first
822 this.$first = function() { return this.$index() === 0; };
823 /// @return bool whether the current step is last
824 this.$last = function() { return this.$index() === steps
.length
-1; };
825 this.$maxVisit = function() { return maxVisited
; };
826 this.$validStep = function() {
827 return steps
[selectedIndex
] && steps
[selectedIndex
].isStepValid();
829 this.iconFor = function(index
) {
830 if (index
< this.$index()) return 'crm-i fa-check';
831 if (index
=== this.$index()) return 'crm-i fa-angle-double-right';
834 this.isSelectable = function(step
) {
835 if (step
.selected
) return false;
836 return this.$validStep();
839 /*** @param Object step the $scope of the step */
840 this.select = function(step
) {
841 angular
.forEach(steps
, function(otherStep
, otherKey
) {
842 otherStep
.selected
= (otherStep
=== step
);
843 if (otherStep
=== step
&& maxVisited
< otherKey
) maxVisited
= otherKey
;
845 selectedIndex
= findIndex();
847 /*** @param Object step the $scope of the step */
848 this.add = function(step
) {
849 if (steps
.length
=== 0) {
850 step
.selected
= true;
854 steps
.sort(function(a
,b
){
855 return a
.crmUiWizardStep
- b
.crmUiWizardStep
;
857 selectedIndex
= findIndex();
859 this.remove = function(step
) {
861 angular
.forEach(steps
, function(otherStep
, otherKey
) {
862 if (otherStep
=== step
) key
= otherKey
;
865 steps
.splice(key
, 1);
868 this.goto = function(index
) {
869 if (index
< 0) index
= 0;
870 if (index
>= steps
.length
) index
= steps
.length
-1;
871 this.select(steps
[index
]);
873 this.previous = function() { this.goto(this.$index()-1); };
874 this.next = function() { this.goto(this.$index()+1); };
875 if ($scope
.crmUiWizard
) {
876 $parse($scope
.crmUiWizard
).assign($scope
.$parent
, this);
879 link: function (scope
, element
, attrs
) {
880 scope
.ts
= CRM
.ts(null);
882 element
.find('.crm-wizard-buttons button[ng-click^=crmUiWizardCtrl]').click(function () {
883 // These values are captured inside the click handler to ensure the
884 // positions/sizes of the elements are captured at the time of the
885 // click vs. at the time this directive is initialized.
886 var topOfWizard
= element
.offset().top
;
887 var heightOfMenu
= $('#civicrm-menu').height() || 0;
890 // stop any other animations that might be happening...
892 // gracefully slide the user to the top of the wizard
893 .animate({scrollTop
: topOfWizard
- heightOfMenu
}, 1000);
899 // Use this to add extra markup to wizard
900 .directive('crmUiWizardButtons', function() {
902 require
: '^crmUiWizard',
905 template
: '<span ng-transclude></span>',
907 link: function (scope
, element
, attrs
, crmUiWizardCtrl
) {
908 var realButtonsEl
= $(element
).closest('.crm-wizard').find('.crm-wizard-buttons');
909 $(element
).appendTo(realButtonsEl
);
914 // Example for Font Awesome: <button crm-icon="fa-check">Save</button>
915 // Example for jQuery UI (deprecated): <button crm-icon="fa-check">Save</button>
916 .directive('crmIcon', function() {
919 link: function (scope
, element
, attrs
) {
920 if (element
.is('[crm-ui-tab]')) {
921 // handled in crmUiTab ctrl
924 if (attrs
.crmIcon
.substring(0,3) == 'fa-') {
925 $(element
).prepend('<i class="crm-i ' + attrs
.crmIcon
+ '" aria-hidden="true"></i> ');
928 $(element
).prepend('<span class="icon ui-icon-' + attrs
.crmIcon
+ '"></span> ');
930 if ($(element
).is('button')) {
931 $(element
).addClass('crm-button');
937 // example: <div crm-ui-wizard-step crm-title="ts('My Title')" ng-form="mySubForm">...content...</div>
938 // If there are any conditional steps, then be sure to set a weight explicitly on *all* steps to maintain ordering.
939 // example: <div crm-ui-wizard-step="100" crm-title="..." ng-if="...">...content...</div>
940 // example with custom classes: <div crm-ui-wizard-step="100" crm-ui-wizard-step-class="ng-animate-out ...">...content...</div>
941 .directive('crmUiWizardStep', function() {
944 require
: ['^crmUiWizard', 'form'],
947 crmTitle
: '@', // expression, evaluates to a printable string
948 crmUiWizardStep
: '@', // int, a weight which determines the ordering of the steps
949 crmUiWizardStepClass
: '@' // string, A list of classes that will be added to the template
951 template
: '<div class="crm-wizard-step {{crmUiWizardStepClass}}" ng-show="selected" ng-transclude/></div>',
953 link: function (scope
, element
, attrs
, ctrls
) {
954 var crmUiWizardCtrl
= ctrls
[0], form
= ctrls
[1];
955 if (scope
.crmUiWizardStep
) {
956 scope
.crmUiWizardStep
= parseInt(scope
.crmUiWizardStep
);
958 scope
.crmUiWizardStep
= nextWeight
++;
960 scope
.isStepValid = function() {
963 crmUiWizardCtrl
.add(scope
);
964 scope
.$on('$destroy', function(){
965 crmUiWizardCtrl
.remove(scope
);
971 // Example: <button crm-confirm="{message: ts('Are you sure you want to continue?')}" on-yes="frobnicate(123)">Frobincate</button>
972 // Example: <button crm-confirm="{type: 'disable', obj: myObject}" on-yes="myObject.is_active=0; myObject.save()">Disable</button>
973 // Example: <button crm-confirm="{templateUrl: '~/path/to/view.html', export: {foo: bar}}" on-yes="frobnicate(123)">Frobincate</button>
974 .directive('crmConfirm', function ($compile
, $rootScope
, $templateRequest
, $q
) {
975 // Helpers to calculate default options for CRM.confirm()
977 'disable': function (options
) {
979 message
: ts('Are you sure you want to disable this?'),
980 options
: {no
: ts('Cancel'), yes
: ts('Disable')},
982 title
: ts('Disable %1?', {
983 1: options
.obj
.title
|| options
.obj
.label
|| options
.obj
.name
|| ts('the record')
987 'revert': function (options
) {
989 message
: ts('Are you sure you want to revert this?'),
990 options
: {no
: ts('Cancel'), yes
: ts('Revert')},
992 title
: ts('Revert %1?', {
993 1: options
.obj
.title
|| options
.obj
.label
|| options
.obj
.name
|| ts('the record')
997 'delete': function (options
) {
999 message
: ts('Are you sure you want to delete this?'),
1000 options
: {no
: ts('Cancel'), yes
: ts('Delete')},
1002 title
: ts('Delete %1?', {
1003 1: options
.obj
.title
|| options
.obj
.label
|| options
.obj
.name
|| ts('the record')
1008 var confirmCount
= 0;
1010 link: function (scope
, element
, attrs
) {
1011 $(element
).click(function () {
1012 var options
= scope
.$eval(attrs
.crmConfirm
);
1013 if (attrs
.title
&& !options
.title
) {
1014 options
.title
= attrs
.title
;
1016 var defaults
= (options
.type
) ? defaultFuncs
[options
.type
](options
) : {};
1018 var tpl
= null, stubId
= null;
1019 if (!options
.message
) {
1020 if (options
.templateUrl
) {
1021 tpl
= $templateRequest(options
.templateUrl
);
1023 else if (options
.template
) {
1024 tpl
= options
.template
;
1027 stubId
= 'crmUiConfirm_' + (++confirmCount
);
1028 options
.message
= '<div id="' + stubId
+ '"></div>';
1032 CRM
.confirm(_
.extend(defaults
, options
))
1033 .on('crmConfirm:yes', function() { scope
.$apply(attrs
.onYes
); })
1034 .on('crmConfirm:no', function() { scope
.$apply(attrs
.onNo
); });
1036 if (tpl
&& stubId
) {
1037 $q
.when(tpl
, function(html
) {
1038 var scope
= options
.scope
|| $rootScope
.$new();
1039 if (options
.export) {
1040 angular
.extend(scope
, options
.export);
1042 var linker
= $compile(html
);
1043 $('#' + stubId
).append($(linker(scope
)));
1051 // Sets document title & page title; attempts to override CMS title markup for the latter
1052 // WARNING: Use only once per route!
1053 // WARNING: This directive works only if your AngularJS base page does not
1054 // set a custom title (i.e., it has an initial title of "CiviCRM"). See the
1055 // global variables pageTitle and documentTitle.
1056 // Example (same title for both): <h1 crm-page-title>{{ts('Hello')}}</h1>
1057 // Example (separate document title): <h1 crm-document-title="ts('Hello')" crm-page-title><i class="crm-i fa-flag" aria-hidden="true"></i>{{ts('Hello')}}</h1>
1058 .directive('crmPageTitle', function($timeout
) {
1061 crmDocumentTitle
: '='
1063 link: function(scope
, $el
, attrs
) {
1065 $timeout(function() {
1066 var newPageTitle
= _
.trim($el
.html()),
1067 newDocumentTitle
= scope
.crmDocumentTitle
|| $el
.text();
1068 document
.title
= $('title').text().replace(documentTitle
, newDocumentTitle
);
1069 // If the CMS has already added title markup to the page, use it
1070 $('h1').not('.crm-container h1').each(function() {
1071 if (_
.trim($(this).html()) === pageTitle
) {
1072 $(this).addClass('crm-page-title').html(newPageTitle
);
1076 pageTitle
= newPageTitle
;
1077 documentTitle
= newDocumentTitle
;
1081 scope
.$watch(function() {return scope
.crmDocumentTitle
+ $el
.html();}, update
);
1086 // Editable text using ngModel & html5 contenteditable
1087 // Usage: <span crm-ui-editable ng-model="my.data">{{ my.data }}</span>
1088 .directive("crmUiEditable", function() {
1095 link: function(scope
, element
, attrs
, ngModel
) {
1099 var htmlVal
= element
.html();
1101 htmlVal
= scope
.defaultValue
|| '';
1102 element
.text(htmlVal
);
1104 ngModel
.$setViewValue(htmlVal
);
1107 ngModel
.$render = function() {
1108 element
.text(ngModel
.$viewValue
|| scope
.defaultValue
|| '');
1111 // Special handling for enter and escape keys
1112 element
.on('keydown', function(e
) {
1113 // Enter: prevent line break and save
1114 if (e
.which
=== 13) {
1119 if (e
.which
=== 27) {
1120 element
.text(ngModel
.$viewValue
|| scope
.defaultValue
|| '');
1125 element
.on("blur change", function() {
1129 element
.attr('contenteditable', 'true').addClass('crm-editable-enabled');
1134 .run(function($rootScope
, $location
) {
1135 /// Example: <button ng-click="goto('home')">Go home!</button>
1136 $rootScope
.goto = function(path
) {
1137 $location
.path(path
);
1139 // useful for debugging: $rootScope.log = console.log || function() {};
1142 })(angular
, CRM
.$, CRM
._
);