docs/embed.md - Use example prefix that doesn't conflict with built-ins
[civicrm-core.git] / ext / afform / core / ang / afCore / Api3Ctrl.js
1 (function(angular, $, _) {
2
3 angular.module('afCore').directive('afApi3Ctrl', function() {
4 return {
5 restrict: 'EA',
6 scope: {
7 afApi3Ctrl: '=',
8 afApi3: '@',
9 afApi3Refresh: '@',
10 onRefresh: '@'
11 },
12 controllerAs: 'afApi3Ctrl',
13 controller: function($scope, $parse, crmThrottle, crmApi) {
14 var ctrl = this;
15
16 // CONSIDER: Trade-offs of upfront vs ongoing evaluation.
17 var parts = $parse($scope.afApi3)($scope.$parent);
18 ctrl.entity = parts[0];
19 ctrl.action = parts[1];
20 ctrl.params = parts[2];
21 ctrl.result = {};
22 ctrl.loading = ctrl.firstLoad = true;
23
24 ctrl.refresh = function refresh() {
25 ctrl.loading = true;
26 crmThrottle(function () {
27 return crmApi(ctrl.entity, ctrl.action, ctrl.params)
28 .then(function (response) {
29 ctrl.result = response;
30 ctrl.loading = ctrl.firstLoad = false;
31 if ($scope.onRefresh) {
32 $scope.$parent.$eval($scope.onRefresh, ctrl);
33 }
34 });
35 });
36 };
37
38 $scope.afApi3Ctrl = this;
39
40 var mode = $scope.afApi3Refresh ? $scope.afApi3Refresh : 'auto';
41 switch (mode) {
42 case 'auto': $scope.$watchCollection('afApi3Ctrl.params', ctrl.refresh); break;
43 case 'init': ctrl.refresh(); break;
44 case 'manual': break;
45 default: throw 'Unrecognized refresh mode: '+ mode;
46 }
47 }
48 };
49 });
50
51 })(angular, CRM.$, CRM._);