CRM-15578 - crmMailingToken - Basic implementation
[civicrm-core.git] / js / angular-crmMailing2-directives.js
CommitLineData
5d72b4e2
TO
1(function (angular, $, _) {
2 var partialUrl = function (relPath) {
3 return CRM.resourceUrls['civicrm'] + '/partials/crmMailing2/' + relPath;
4 };
5
6 var crmMailing2 = angular.module('crmMailing2');
7
8 // example: <input name="subject" /> <input crm-mailing-token crm-for="subject"/>
9 // WISHLIST: Instead of global CRM.crmMailing.mailTokens, accept token list as an input
10 crmMailing2.directive('crmMailingToken', function () {
11 return {
12 scope: {
13 crmFor: '@'
14 },
15 template: '<input type="text" class="crmMailingToken" />',
16 link: function (scope, element, attrs) {
17 // 1. Find the corresponding input element (crmFor)
18
19 var form = $(element).closest('form');
20 var crmForEl = $('input[name="' + attrs.crmFor + '"],textarea[name="' + attrs.crmFor + '"]', form);
21 if (form.length != 1 || crmForEl.length != 1) {
22 if (console.log)
23 console.log('crmMailingToken cannot be matched to input element. Expected to find one form and one input.', form.length, crmForEl.length);
24 return;
25 }
26
27 // 2. Setup the token selector
28 $(element).select2({width: "10em",
29 dropdownAutoWidth: true,
30 data: CRM.crmMailing.mailTokens,
31 placeholder: ts('Insert')
32 });
33 $(element).on('select2-selecting', function (e) {
34 var origVal = crmForEl.val();
35 var origPos = crmForEl[0].selectionStart;
36 var newVal = origVal.substring(0, origPos) + e.val + origVal.substring(origPos, origVal.length);
37 crmForEl.val(newVal);
38 var newPos = (origPos + e.val.length);
39 crmForEl[0].selectionStart = newPos;
40 crmForEl[0].selectionEnd = newPos;
41
42 $(element).select2('close').select2('val', '');
43 crmForEl.triggerHandler('change');
44 crmForEl.focus();
45
46 e.preventDefault();
47 });
48 }
49 };
50 });
51
52})(angular, CRM.$, CRM._);