1 /// crmUi: Sundry UI helpers
2 (function (angular
, $, _
) {
6 angular
.module('crmUi', [])
8 // example <div crm-ui-accordion crm-title="ts('My Title')" crm-collapsed="true">...content...</div>
9 // WISHLIST: crmCollapsed should support two-way/continous binding
10 .directive('crmUiAccordion', function() {
15 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>',
17 link: function (scope
, element
, attrs
) {
19 'crm-accordion-wrapper': true,
20 collapsed
: scope
.crmUiAccordion
.collapsed
23 scope
.$watch('crmUiAccordion', function(crmUiAccordion
) {
24 if (crmUiAccordion
&& crmUiAccordion
.help
) {
25 scope
.help
= crmUiAccordion
.help
.clone({}, {
26 title
: crmUiAccordion
.title
35 // crmUiAlert({text: 'My text', title: 'My title', type: 'error'});
36 // crmUiAlert({template: '<a ng-click="ok()">Hello</a>', scope: $scope.$new()});
37 // var h = crmUiAlert({templateUrl: '~/crmFoo/alert.html', scope: $scope.$new()});
39 .service('crmUiAlert', function($compile
, $rootScope
, $templateRequest
, $q
) {
41 return function crmUiAlert(params
) {
42 var id
= 'crmUiAlert_' + (++count
);
44 if (params
.templateUrl
) {
45 tpl
= $templateRequest(params
.templateUrl
);
47 else if (params
.template
) {
48 tpl
= params
.template
;
51 params
.text
= '<div id="' + id
+ '"></div>'; // temporary stub
53 var result
= CRM
.alert(params
.text
, params
.title
, params
.type
, params
.options
);
55 $q
.when(tpl
, function(html
) {
56 var scope
= params
.scope
|| $rootScope
.$new();
57 var linker
= $compile(html
);
58 $('#' + id
).append($(linker(scope
)));
65 // Simple wrapper around $.crmDatepicker.
66 // example with no time input: <input crm-ui-datepicker="{time: false}" ng-model="myobj.datefield"/>
67 // example with custom date format: <input crm-ui-datepicker="{date: 'm/d/y'}" ng-model="myobj.datefield"/>
68 .directive('crmUiDatepicker', function () {
75 link: function (scope
, element
, attrs
, ngModel
) {
76 ngModel
.$render = function () {
77 element
.val(ngModel
.$viewValue
).change();
81 .crmDatepicker(scope
.crmUiDatepicker
)
82 .on('change', function() {
83 var requiredLength
= 19;
84 if (scope
.crmUiDatepicker
&& scope
.crmUiDatepicker
.time
=== false) {
87 if (scope
.crmUiDatepicker
&& scope
.crmUiDatepicker
.date
=== false) {
90 ngModel
.$setValidity('incompleteDateTime', !($(this).val().length
&& $(this).val().length
!== requiredLength
));
96 // Display debug information (if available)
97 // For richer DX, checkout Batarang/ng-inspector (Chrome/Safari), or AngScope/ng-inspect (Firefox).
98 // example: <div crm-ui-debug="myobject" />
99 .directive('crmUiDebug', function ($location
) {
105 template: function() {
106 var args
= $location
.search();
107 return (args
&& args
.angularDebug
) ? '<div crm-ui-accordion=\'{title: ts("Debug (%1)", {1: crmUiDebug}), collapsed: true}\'><pre>{{data|json}}</pre></div>' : '';
109 link: function(scope
, element
, attrs
) {
110 var args
= $location
.search();
111 if (args
&& args
.angularDebug
) {
112 scope
.ts
= CRM
.ts(null);
113 scope
.$parent
.$watch(attrs
.crmUiDebug
, function(data
) {
121 // Display a field/row in a field list
122 // example: <div crm-ui-field="{title: ts('My Field')}"> {{mydata}} </div>
123 // example: <div crm-ui-field="{name: 'subform.myfield', title: ts('My Field')}"> <input crm-ui-id="subform.myfield" name="myfield" /> </div>
124 // example: <div crm-ui-field="{name: 'subform.myfield', title: ts('My Field')}"> <input crm-ui-id="subform.myfield" name="myfield" required /> </div>
125 // example: <div crm-ui-field="{name: 'subform.myfield', title: ts('My Field'), help: hs('help_field_name')}"> {{mydata}} </div>
126 .directive('crmUiField', function() {
127 // Note: When writing new templates, the "label" position is particular. See/patch "var label" below.
129 default: '~/crmUi/field.html',
130 checkbox
: '~/crmUi/field-cb.html'
134 require
: '^crmUiIdScope',
137 // {title, name, help, helpFile}
140 templateUrl: function(tElement
, tAttrs
){
141 var layout
= tAttrs
.crmLayout
? tAttrs
.crmLayout
: 'default';
142 return templateUrls
[layout
];
145 link: function (scope
, element
, attrs
, crmUiIdCtrl
) {
146 $(element
).addClass('crm-section');
148 scope
.$watch('crmUiField', function(crmUiField
) {
149 if (crmUiField
&& crmUiField
.help
) {
150 scope
.help
= crmUiField
.help
.clone({}, {
151 title
: crmUiField
.title
159 // 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>
160 .directive('crmUiId', function () {
162 require
: '^crmUiIdScope',
165 pre: function (scope
, element
, attrs
, crmUiIdCtrl
) {
166 var id
= crmUiIdCtrl
.get(attrs
.crmUiId
);
167 element
.attr('id', id
);
173 // for example, see crmUiHelp
174 .service('crmUiHelp', function(){
175 // example: var h = new FieldHelp({id: 'foo'}); h.open();
176 function FieldHelp(options
) {
177 this.options
= options
;
179 angular
.extend(FieldHelp
.prototype, {
181 return this.options
[n
];
183 open
: function open() {
184 CRM
.help(this.options
.title
, {id
: this.options
.id
, file
: this.options
.file
});
186 clone
: function clone(options
, defaults
) {
187 return new FieldHelp(angular
.extend({}, defaults
, this.options
, options
));
191 // example: var hs = crmUiHelp({file: 'CRM/Foo/Bar'});
192 return function(defaults
){
193 // example: hs('myfield')
194 // example: hs({id: 'myfield', title: 'Foo Bar', file: 'Whiz/Bang'})
195 return function(options
) {
196 if (_
.isString(options
)) {
197 options
= {id
: options
};
199 return new FieldHelp(angular
.extend({}, defaults
, options
));
204 // Display a help icon
205 // Example: Use a default *.hlp file
206 // scope.hs = crmUiHelp({file: 'Path/To/Help/File'});
207 // HTML: <a crm-ui-help="hs({title:ts('My Field'), id:'my_field'})">
208 // Example: Use an explicit *.hlp file
209 // HTML: <a crm-ui-help="hs({title:ts('My Field'), id:'my_field', file:'CRM/Foo/Bar'})">
210 .directive('crmUiHelp', function() {
213 link: function(scope
, element
, attrs
) {
214 setTimeout(function() {
215 var crmUiHelp
= scope
.$eval(attrs
.crmUiHelp
);
216 var title
= crmUiHelp
&& crmUiHelp
.get('title') ? ts('%1 Help', {1: crmUiHelp
.get('title')}) : ts('Help');
217 element
.attr('title', title
);
221 .addClass('helpicon')
223 .on('click', function(e
) {
225 scope
.$eval(attrs
.crmUiHelp
).open();
231 // 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>
232 .directive('crmUiFor', function ($parse
, $timeout
) {
234 require
: '^crmUiIdScope',
236 template
: '<span ng-class="cssClasses"><span ng-transclude/><span crm-ui-visible="crmIsRequired" class="crm-marker" title="This field is required.">*</span></span>',
238 link: function (scope
, element
, attrs
, crmUiIdCtrl
) {
239 scope
.crmIsRequired
= false;
240 scope
.cssClasses
= {};
242 if (!attrs
.crmUiFor
) return;
244 var id
= crmUiIdCtrl
.get(attrs
.crmUiFor
);
245 element
.attr('for', id
);
248 var updateCss = function () {
249 scope
.cssClasses
['crm-error'] = !ngModel
.$valid
&& !ngModel
.$pristine
;
252 // Note: if target element is dynamically generated (eg via ngInclude), then it may not be available
253 // immediately for initialization. Use retries/retryDelay to initialize such elements.
254 var init = function (retries
, retryDelay
) {
255 var input
= $('#' + id
);
256 if (input
.length
=== 0) {
259 init(retries
-1, retryDelay
);
265 var tgtScope
= scope
;//.$parent;
266 if (attrs
.crmDepth
) {
267 for (var i
= attrs
.crmDepth
; i
> 0; i
--) {
268 tgtScope
= tgtScope
.$parent
;
272 if (input
.attr('ng-required')) {
273 scope
.crmIsRequired
= scope
.$parent
.$eval(input
.attr('ng-required'));
274 scope
.$parent
.$watch(input
.attr('ng-required'), function (isRequired
) {
275 scope
.crmIsRequired
= isRequired
;
279 scope
.crmIsRequired
= input
.prop('required');
282 ngModel
= $parse(attrs
.crmUiFor
)(tgtScope
);
284 ngModel
.$viewChangeListeners
.push(updateCss
);
295 // Define a scope in which a name like "subform.foo" maps to a unique ID.
296 // 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>
297 .directive('crmUiIdScope', function () {
301 controllerAs
: 'crmUiIdCtrl',
302 controller: function($scope
) {
304 this.get = function(name
) {
306 ids
[name
] = "crmUiId_" + (++uidCount
);
311 link: function (scope
, element
, attrs
) {}
315 // Display an HTML blurb inside an IFRAME.
316 // example: <iframe crm-ui-iframe="getHtmlContent()"></iframe>
317 // example: <iframe crm-ui-iframe crm-ui-iframe-src="getUrl()"></iframe>
318 .directive('crmUiIframe', function ($parse
) {
321 crmUiIframeSrc
: '@', // expression which evaluates to a URL
322 crmUiIframe
: '@' // expression which evaluates to HTML content
324 link: function (scope
, elm
, attrs
) {
325 var iframe
= $(elm
)[0];
326 iframe
.setAttribute('width', '100%');
327 iframe
.setAttribute('frameborder', '0');
329 var refresh = function () {
330 if (attrs
.crmUiIframeSrc
) {
331 iframe
.setAttribute('src', scope
.$parent
.$eval(attrs
.crmUiIframeSrc
));
334 var iframeHtml
= scope
.$parent
.$eval(attrs
.crmUiIframe
);
336 var doc
= iframe
.document
;
337 if (iframe
.contentDocument
) {
338 doc
= iframe
.contentDocument
;
340 else if (iframe
.contentWindow
) {
341 doc
= iframe
.contentWindow
.document
;
345 doc
.writeln(iframeHtml
);
350 // If the iframe is in a dialog, respond to resize events
351 $(elm
).parent().on('dialogresize dialogopen', function(e
, ui
) {
352 $(this).css({padding
: '0', margin
: '0', overflow
: 'hidden'});
353 iframe
.setAttribute('height', '' + $(this).innerHeight() + 'px');
356 scope
.$parent
.$watch(attrs
.crmUiIframe
, refresh
);
362 // <a ng-click="$broadcast('my-insert-target', 'some new text')>Insert</a>
363 // <textarea crm-ui-insert-rx='my-insert-target'></textarea>
364 // TODO Consider ways to separate the plain-text/rich-text implementations
365 .directive('crmUiInsertRx', function() {
367 link: function(scope
, element
, attrs
) {
368 scope
.$on(attrs
.crmUiInsertRx
, function(e
, tokenName
) {
369 var id
= element
.attr('id');
370 if (CKEDITOR
.instances
[id
]) {
371 CKEDITOR
.instances
[id
].insertText(tokenName
);
372 $(element
).select2('close').select2('val', '');
373 CKEDITOR
.instances
[id
].focus();
376 var crmForEl
= $('#' + id
);
377 var origVal
= crmForEl
.val();
378 var origPos
= crmForEl
[0].selectionStart
;
379 var newVal
= origVal
.substring(0, origPos
) + tokenName
+ origVal
.substring(origPos
, origVal
.length
);
380 crmForEl
.val(newVal
);
381 var newPos
= (origPos
+ tokenName
.length
);
382 crmForEl
[0].selectionStart
= newPos
;
383 crmForEl
[0].selectionEnd
= newPos
;
385 $(element
).select2('close').select2('val', '');
386 crmForEl
.triggerHandler('change');
394 // Define a rich text editor.
395 // example: <textarea crm-ui-id="myForm.body_html" crm-ui-richtext name="body_html" ng-model="mailing.body_html"></textarea>
396 .directive('crmUiRichtext', function ($timeout
) {
399 link: function (scope
, elm
, attr
, ngModel
) {
400 var ck
= CKEDITOR
.replace(elm
[0]);
403 _
.extend(ck
.config
, {
406 filebrowserBrowseUrl
: CRM
.crmUi
.browseUrl
+ '?cms=civicrm&type=files',
407 filebrowserImageBrowseUrl
: CRM
.crmUi
.browseUrl
+ '?cms=civicrm&type=images',
408 filebrowserFlashBrowseUrl
: CRM
.crmUi
.browseUrl
+ '?cms=civicrm&type=flash',
409 filebrowserUploadUrl
: CRM
.crmUi
.uploadUrl
+ '?cms=civicrm&type=files',
410 filebrowserImageUploadUrl
: CRM
.crmUi
.uploadUrl
+ '?cms=civicrm&type=images',
411 filebrowserFlashUploadUrl
: CRM
.crmUi
.uploadUrl
+ '?cms=civicrm&type=flash',
420 ck
.on('blur', function(){
422 scope
.$eval(attr
.ngBlur
);
427 // CRM-16445 - When one inserts an image, none of these events seem to fire at the right time:
428 // afterCommandExec, afterInsertHtml, afterPaste, afterSetData, change, insertElement,
429 // insertHtml, insertText, pasteState. It seems that 'pasteState' is the general equivalent of
430 // what 'change' should be, except (in the case of image insertion) it fires too soon.
431 // The 'key' event is needed to detect changes in "Source" mode.
433 angular
.forEach(['key', 'pasteState'], function(evName
){
434 ck
.on(evName
, function(evt
) {
435 $timeout
.cancel(debounce
);
436 debounce
= $timeout(function() {
437 ngModel
.$setViewValue(ck
.getData());
442 ngModel
.$render = function (value
) {
443 ck
.setData(ngModel
.$viewValue
);
449 // Display a lock icon (based on a boolean).
450 // example: <a crm-ui-lock binding="mymodel.boolfield"></a>
451 // example: <a crm-ui-lock
452 // binding="mymodel.boolfield"
453 // title-locked="ts('Boolfield is locked')"
454 // title-unlocked="ts('Boolfield is unlocked')"></a>
455 .directive('crmUiLock', function ($parse
, $rootScope
) {
456 var defaultVal = function (defaultValue
) {
457 var f = function (scope
) {
460 f
.assign = function (scope
, value
) {
466 // like $parse, but accepts a defaultValue in case expr is undefined
467 var parse = function (expr
, defaultValue
) {
468 return expr
? $parse(expr
) : defaultVal(defaultValue
);
473 link: function (scope
, element
, attrs
) {
474 var binding
= parse(attrs
.binding
, true);
475 var titleLocked
= parse(attrs
.titleLocked
, ts('Locked'));
476 var titleUnlocked
= parse(attrs
.titleUnlocked
, ts('Unlocked'));
478 $(element
).addClass('ui-icon lock-button');
479 var refresh = function () {
480 var locked
= binding(scope
);
483 .removeClass('ui-icon-unlocked')
484 .addClass('ui-icon-locked')
485 .prop('title', titleLocked(scope
))
490 .removeClass('ui-icon-locked')
491 .addClass('ui-icon-unlocked')
492 .prop('title', titleUnlocked(scope
))
497 $(element
).click(function () {
498 binding
.assign(scope
, !binding(scope
));
500 $rootScope
.$digest();
503 scope
.$watch(attrs
.binding
, refresh
);
504 scope
.$watch(attrs
.titleLocked
, refresh
);
505 scope
.$watch(attrs
.titleUnlocked
, refresh
);
512 // CrmUiOrderCtrl is a controller class which manages sort orderings.
514 // JS: $scope.myOrder = new CrmUiOrderCtrl(['+field1', '-field2]);
515 // $scope.myOrder.toggle('field1');
516 // $scope.myOrder.setDir('field2', '');
517 // HTML: <tr ng-repeat="... | order:myOrder.get()">...</tr>
518 .service('CrmUiOrderCtrl', function(){
520 function CrmUiOrderCtrl(defaults
){
521 this.values
= defaults
;
523 angular
.extend(CrmUiOrderCtrl
.prototype, {
524 get: function get() {
527 getDir
: function getDir(name
) {
528 if (this.values
.indexOf(name
) >= 0 || this.values
.indexOf('+' + name
) >= 0) {
531 if (this.values
.indexOf('-' + name
) >= 0) {
536 // @return bool TRUE if something is removed
537 remove
: function remove(name
) {
538 var idx
= this.values
.indexOf(name
);
540 this.values
.splice(idx
, 1);
547 setDir
: function setDir(name
, dir
) {
548 return this.toggle(name
, dir
);
550 // Toggle sort order on a field.
551 // To set a specific order, pass optional parameter 'next' ('+', '-', or '').
552 toggle
: function toggle(name
, next
) {
553 if (!next
&& next
!== '') {
555 if (this.remove(name
) || this.remove('+' + name
)) {
558 if (this.remove('-' + name
)) {
564 this.values
.unshift('+' + name
);
566 else if (next
== '-') {
567 this.values
.unshift('-' + name
);
571 return CrmUiOrderCtrl
;
574 // Define a controller which manages sort order. You may interact with the controller
575 // directly ("myOrder.toggle('fieldname')") order using the helper, crm-ui-order-by.
577 // <span crm-ui-order="{var: 'myOrder', defaults: {'-myField'}}"></span>
578 // <th><a crm-ui-order-by="[myOrder,'myField']">My Field</a></th>
579 // <tr ng-repeat="... | order:myOrder.get()">...</tr>
580 // <button ng-click="myOrder.toggle('myField')">
581 .directive('crmUiOrder', function(CrmUiOrderCtrl
) {
583 link: function(scope
, element
, attrs
){
584 var options
= angular
.extend({var: 'crmUiOrderBy'}, scope
.$eval(attrs
.crmUiOrder
));
585 scope
[options
.var] = new CrmUiOrderCtrl(options
.defaults
);
590 // For usage, see crmUiOrder (above)
591 .directive('crmUiOrderBy', function() {
593 link: function(scope
, element
, attrs
) {
594 function updateClass(crmUiOrderCtrl
, name
) {
595 var dir
= crmUiOrderCtrl
.getDir(name
);
597 .toggleClass('sorting_asc', dir
=== '+')
598 .toggleClass('sorting_desc', dir
=== '-')
599 .toggleClass('sorting', dir
=== '');
602 element
.on('click', function(e
){
603 var tgt
= scope
.$eval(attrs
.crmUiOrderBy
);
604 tgt
[0].toggle(tgt
[1]);
605 updateClass(tgt
[0], tgt
[1]);
610 var tgt
= scope
.$eval(attrs
.crmUiOrderBy
);
611 updateClass(tgt
[0], tgt
[1]);
616 // Display a fancy SELECT (based on select2).
617 // usage: <select crm-ui-select="{placeholder:'Something',allowClear:true,...}" ng-model="myobj.field"><option...></select>
618 .directive('crmUiSelect', function ($parse
, $timeout
) {
624 link: function (scope
, element
, attrs
, ngModel
) {
625 // In cases where UI initiates update, there may be an extra
626 // call to refreshUI, but it doesn't create a cycle.
629 ngModel
.$render = function () {
630 $timeout(function () {
631 // ex: msg_template_id adds new item then selects it; use $timeout to ensure that
632 // new item is added before selection is made
633 element
.select2('val', ngModel
.$modelValue
);
637 function refreshModel() {
638 var oldValue
= ngModel
.$viewValue
, newValue
= element
.select2('val');
639 if (oldValue
!= newValue
) {
640 scope
.$parent
.$apply(function () {
641 ngModel
.$setViewValue(newValue
);
647 // TODO watch select2-options
648 element
.select2(scope
.crmUiSelect
|| {});
650 element
.on('change', refreshModel
);
651 $timeout(ngModel
.$render
);
660 // Render a crmEntityRef widget
661 // usage: <input crm-entityref="{entity: 'Contact', select: {allowClear:true}}" ng-model="myobj.field" />
662 .directive('crmEntityref', function ($parse
, $timeout
) {
668 link: function (scope
, element
, attrs
, ngModel
) {
669 // In cases where UI initiates update, there may be an extra
670 // call to refreshUI, but it doesn't create a cycle.
672 ngModel
.$render = function () {
673 $timeout(function () {
674 // ex: msg_template_id adds new item then selects it; use $timeout to ensure that
675 // new item is added before selection is made
676 element
.select2('val', ngModel
.$modelValue
);
679 function refreshModel() {
680 var oldValue
= ngModel
.$viewValue
, newValue
= element
.select2('val');
681 if (oldValue
!= newValue
) {
682 scope
.$parent
.$apply(function () {
683 ngModel
.$setViewValue(newValue
);
689 // TODO can we infer "entity" from model?
690 element
.crmEntityRef(scope
.crmEntityref
|| {});
691 element
.on('change', refreshModel
);
692 $timeout(ngModel
.$render
);
700 // example <div crm-ui-tab crm-title="ts('My Title')">...content...</div>
701 // WISHLIST: use a full Angular component instead of an incomplete jQuery wrapper
702 .directive('crmUiTab', function($parse
) {
704 require
: '^crmUiTabSet',
710 template
: '<div ng-transclude></div>',
712 link: function (scope
, element
, attrs
, crmUiTabSetCtrl
) {
713 crmUiTabSetCtrl
.add(scope
);
718 // 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>
719 .directive('crmUiTabSet', function() {
725 templateUrl
: '~/crmUi/tabset.html',
727 controllerAs
: 'crmUiTabSetCtrl',
728 controller: function($scope
, $parse
) {
729 var tabs
= $scope
.tabs
= []; // array<$scope>
730 this.add = function(tab
) {
731 if (!tab
.id
) throw "Tab is missing 'id'";
735 link: function (scope
, element
, attrs
) {}
739 // Generic, field-independent form validator.
740 // example: <span ng-model="placeholder" crm-ui-validate="foo && bar || whiz" />
741 // example: <span ng-model="placeholder" crm-ui-validate="foo && bar || whiz" crm-ui-validate-name="myError" />
742 .directive('crmUiValidate', function() {
746 link: function(scope
, element
, attrs
, ngModel
) {
747 var validationKey
= attrs
.crmUiValidateName
? attrs
.crmUiValidateName
: 'crmUiValidate';
748 scope
.$watch(attrs
.crmUiValidate
, function(newValue
){
749 ngModel
.$setValidity(validationKey
, !!newValue
);
755 // like ng-show, but hides/displays elements using "visibility" which maintains positioning
756 // example <div crm-ui-visible="false">...content...</div>
757 .directive('crmUiVisible', function($parse
) {
763 link: function (scope
, element
, attrs
) {
764 var model
= $parse(attrs
.crmUiVisible
);
765 function updatecChildren() {
766 element
.css('visibility', model(scope
.$parent
) ? 'inherit' : 'hidden');
769 scope
.$parent
.$watch(attrs
.crmUiVisible
, updatecChildren
);
774 // 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>
775 // Note: "myWizardCtrl" has various actions/properties like next() and $first().
776 // WISHLIST: Allow each step to determine if it is "complete" / "valid" / "selectable"
777 // WISHLIST: Allow each step to enable/disable (show/hide) itself
778 .directive('crmUiWizard', function() {
784 templateUrl
: '~/crmUi/wizard.html',
786 controllerAs
: 'crmUiWizardCtrl',
787 controller: function($scope
, $parse
) {
788 var steps
= $scope
.steps
= []; // array<$scope>
789 var crmUiWizardCtrl
= this;
791 var selectedIndex
= null;
793 var findIndex = function() {
795 angular
.forEach(steps
, function(step
, stepKey
) {
796 if (step
.selected
) found
= stepKey
;
801 /// @return int the index of the current step
802 this.$index = function() { return selectedIndex
; };
803 /// @return bool whether the currentstep is first
804 this.$first = function() { return this.$index() === 0; };
805 /// @return bool whether the current step is last
806 this.$last = function() { return this.$index() === steps
.length
-1; };
807 this.$maxVisit = function() { return maxVisited
; };
808 this.$validStep = function() {
809 return steps
[selectedIndex
] && steps
[selectedIndex
].isStepValid();
811 this.iconFor = function(index
) {
812 if (index
< this.$index()) return '√';
813 if (index
=== this.$index()) return '»';
816 this.isSelectable = function(step
) {
817 if (step
.selected
) return false;
819 angular
.forEach(steps
, function(otherStep
, otherKey
) {
820 if (step
=== otherStep
&& otherKey
<= maxVisited
) result
= true;
825 /*** @param Object step the $scope of the step */
826 this.select = function(step
) {
827 angular
.forEach(steps
, function(otherStep
, otherKey
) {
828 otherStep
.selected
= (otherStep
=== step
);
829 if (otherStep
=== step
&& maxVisited
< otherKey
) maxVisited
= otherKey
;
831 selectedIndex
= findIndex();
833 /*** @param Object step the $scope of the step */
834 this.add = function(step
) {
835 if (steps
.length
=== 0) {
836 step
.selected
= true;
840 steps
.sort(function(a
,b
){
841 return a
.crmUiWizardStep
- b
.crmUiWizardStep
;
843 selectedIndex
= findIndex();
845 this.remove = function(step
) {
847 angular
.forEach(steps
, function(otherStep
, otherKey
) {
848 if (otherStep
=== step
) key
= otherKey
;
851 steps
.splice(key
, 1);
854 this.goto = function(index
) {
855 if (index
< 0) index
= 0;
856 if (index
>= steps
.length
) index
= steps
.length
-1;
857 this.select(steps
[index
]);
859 this.previous = function() { this.goto(this.$index()-1); };
860 this.next = function() { this.goto(this.$index()+1); };
861 if ($scope
.crmUiWizard
) {
862 $parse($scope
.crmUiWizard
).assign($scope
.$parent
, this);
865 link: function (scope
, element
, attrs
) {
866 scope
.ts
= CRM
.ts(null);
871 // Use this to add extra markup to wizard
872 .directive('crmUiWizardButtons', function() {
874 require
: '^crmUiWizard',
877 template
: '<span ng-transclude></span>',
879 link: function (scope
, element
, attrs
, crmUiWizardCtrl
) {
880 var realButtonsEl
= $(element
).closest('.crm-wizard').find('.crm-wizard-buttons');
881 $(element
).appendTo(realButtonsEl
);
886 // Example: <button crm-icon="check">Save</button>
887 .directive('crmIcon', function() {
891 link: function (scope
, element
, attrs
) {
892 $(element
).prepend('<span class="icon ui-icon-' + attrs
.crmIcon
+ '"></span> ');
893 if ($(element
).is('button')) {
894 $(element
).addClass('crm-button');
900 // example: <div crm-ui-wizard-step crm-title="ts('My Title')" ng-form="mySubForm">...content...</div>
901 // If there are any conditional steps, then be sure to set a weight explicitly on *all* steps to maintain ordering.
902 // example: <div crm-ui-wizard-step="100" crm-title="..." ng-if="...">...content...</div>
903 .directive('crmUiWizardStep', function() {
906 require
: ['^crmUiWizard', 'form'],
909 crmTitle
: '@', // expression, evaluates to a printable string
910 crmUiWizardStep
: '@' // int, a weight which determines the ordering of the steps
912 template
: '<div class="crm-wizard-step" ng-show="selected" ng-transclude/></div>',
914 link: function (scope
, element
, attrs
, ctrls
) {
915 var crmUiWizardCtrl
= ctrls
[0], form
= ctrls
[1];
916 if (scope
.crmUiWizardStep
) {
917 scope
.crmUiWizardStep
= parseInt(scope
.crmUiWizardStep
);
919 scope
.crmUiWizardStep
= nextWeight
++;
921 scope
.isStepValid = function() {
924 crmUiWizardCtrl
.add(scope
);
925 element
.on('$destroy', function(){
926 crmUiWizardCtrl
.remove(scope
);
932 // Example: <button crm-confirm="{message: ts('Are you sure you want to continue?')}" on-yes="frobnicate(123)">Frobincate</button>
933 // Example: <button crm-confirm="{type: 'disable', obj: myObject}" on-yes="myObject.is_active=0; myObject.save()">Disable</button>
934 // Example: <button crm-confirm="{templateUrl: '~/path/to/view.html', export: {foo: bar}}" on-yes="frobnicate(123)">Frobincate</button>
935 .directive('crmConfirm', function ($compile
, $rootScope
, $templateRequest
, $q
) {
936 // Helpers to calculate default options for CRM.confirm()
938 'disable': function (options
) {
940 message
: ts('Are you sure you want to disable this?'),
941 options
: {no
: ts('Cancel'), yes
: ts('Disable')},
943 title
: ts('Disable %1?', {
944 1: options
.obj
.title
|| options
.obj
.label
|| options
.obj
.name
|| ts('the record')
948 'revert': function (options
) {
950 message
: ts('Are you sure you want to revert this?'),
951 options
: {no
: ts('Cancel'), yes
: ts('Revert')},
953 title
: ts('Revert %1?', {
954 1: options
.obj
.title
|| options
.obj
.label
|| options
.obj
.name
|| ts('the record')
958 'delete': function (options
) {
960 message
: ts('Are you sure you want to delete this?'),
961 options
: {no
: ts('Cancel'), yes
: ts('Delete')},
963 title
: ts('Delete %1?', {
964 1: options
.obj
.title
|| options
.obj
.label
|| options
.obj
.name
|| ts('the record')
969 var confirmCount
= 0;
971 link: function (scope
, element
, attrs
) {
972 $(element
).click(function () {
973 var options
= scope
.$eval(attrs
.crmConfirm
);
974 if (attrs
.title
&& !options
.title
) {
975 options
.title
= attrs
.title
;
977 var defaults
= (options
.type
) ? defaultFuncs
[options
.type
](options
) : {};
979 var tpl
= null, stubId
= null;
980 if (!options
.message
) {
981 if (options
.templateUrl
) {
982 tpl
= $templateRequest(options
.templateUrl
);
984 else if (options
.template
) {
985 tpl
= options
.template
;
988 stubId
= 'crmUiConfirm_' + (++confirmCount
);
989 options
.message
= '<div id="' + stubId
+ '"></div>';
993 CRM
.confirm(_
.extend(defaults
, options
))
994 .on('crmConfirm:yes', function() { scope
.$apply(attrs
.onYes
); })
995 .on('crmConfirm:no', function() { scope
.$apply(attrs
.onNo
); });
998 $q
.when(tpl
, function(html
) {
999 var scope
= options
.scope
|| $rootScope
.$new();
1000 if (options
.export) {
1001 angular
.extend(scope
, options
.export);
1003 var linker
= $compile(html
);
1004 $('#' + stubId
).append($(linker(scope
)));
1011 .run(function($rootScope
, $location
) {
1012 /// Example: <button ng-click="goto('home')">Go home!</button>
1013 $rootScope
.goto = function(path
) {
1014 $location
.path(path
);
1016 // useful for debugging: $rootScope.log = console.log || function() {};
1020 })(angular
, CRM
.$, CRM
._
);