1 (function(angular
, $, _
) {
2 // example <select crm-mailing-templates crm-mailing="mymailing"></select>
3 angular
.module('crmMailing').directive('crmMailingTemplates', function(crmUiAlert
) {
10 templateUrl
: '~/crmMailing/Templates.html',
11 link: function(scope
, element
, attrs
, ngModel
) {
12 scope
.template
= ngModel
.$viewValue
;
14 var refreshUI
= ngModel
.$render
= function refresuhUI() {
15 scope
.template
= ngModel
.$viewValue
;
16 if (ngModel
.$viewValue
) {
17 $(element
).select2('val', ngModel
.$viewValue
);
21 // @return string HTML representing an option
22 function formatItem(item
) {
24 // return `text` for optgroup
27 return '<span class="crmMailing-template">' + item
.text
+ '</span>';
32 entity
: 'civicrm_msg_templates',
39 placeholder
: "<i class='fa fa-clipboard'></i> Mailing Templates",
40 formatResult
: formatItem
,
41 escapeMarkup: function(m
) {
45 initSelection: function(el
, cb
) {
49 CRM
.api3('MessageTemplate', 'getlist', { params
: { id
: value
}, label_field
: 'msg_title' }).then(function(tlist
) {
54 $(tlist
.values
).each(function(id
, val
) {
56 template
.text
= val
.label
;
64 url
: CRM
.url('civicrm/ajax/rest'),
66 data: function(input
, page_num
) {
70 entity
: 'civicrm_msg_templates',
75 rcpAjaxState
.page_i
= page_num
- rcpAjaxState
.page_n
;
76 var filterParams
= { is_active
: 1, workflow_id
: { "IS NULL": 1 } };
80 page_num
: rcpAjaxState
.page_i
,
81 label_field
: 'msg_title',
82 search_field
: 'msg_title',
87 transport: function(params
) {
88 CRM
.api3('MessageTemplate', 'getlist', params
.data
).then(params
.success
, params
.error
);
90 results: function(data
) {
93 children
: $.map(data
.values
, function(obj
) {
94 return { id
: obj
.id
, text
: obj
.label
};
98 if (rcpAjaxState
.page_i
== 1 && data
.count
) {
99 results
.text
= ts('Message Templates');
102 more
= data
.more_results
;
104 if (more
&& !data
.more_results
) {
105 rcpAjaxState
.page_n
+= rcpAjaxState
.page_i
;
108 return { more
: more
, results
: [ results
] };
113 $(element
).on('select2-selecting', function(e
) {
114 // in here is where the template HTML should be loaded
115 var entity_id
= parseInt(e
.val
);
116 ngModel
.$viewValue
= entity_id
;
118 scope
.$parent
.loadTemplate(scope
.$parent
.$parent
.mailing
, entity_id
);
120 $(element
).select2('close');
125 scope
.$watchCollection("template", refreshUI
);
126 setTimeout(refreshUI
, 50);
132 })(angular
, CRM
.$, CRM
._
);