From 3e447fa777d347a469f6f304ec43d2f43f46b9ec Mon Sep 17 00:00:00 2001 From: Coleman Watts Date: Wed, 6 Feb 2019 21:46:30 -0500 Subject: [PATCH] Add Api4Ctrl --- ext/afform/ang/afformCore.ang.php | 2 +- ext/afform/ang/afformCore/Api4Ctrl.js | 51 +++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 ext/afform/ang/afformCore/Api4Ctrl.js diff --git a/ext/afform/ang/afformCore.ang.php b/ext/afform/ang/afformCore.ang.php index c8b2a48d9b..2a02341632 100644 --- a/ext/afform/ang/afformCore.ang.php +++ b/ext/afform/ang/afformCore.ang.php @@ -10,7 +10,7 @@ return array( 2 => 'ang/afformCore/*/*.js', ), 'css' => array(), - 'requires' => array('crmUi', 'crmUtil'), + 'requires' => array('crmUi', 'crmUtil', 'api4'), 'partials' => array('ang/afformCore'), 'settings' => array(), 'basePages' => [], diff --git a/ext/afform/ang/afformCore/Api4Ctrl.js b/ext/afform/ang/afformCore/Api4Ctrl.js new file mode 100644 index 0000000000..32ae530fd1 --- /dev/null +++ b/ext/afform/ang/afformCore/Api4Ctrl.js @@ -0,0 +1,51 @@ +(function(angular, $, _) { + + angular.module('afformCore').directive('affApi4Ctrl', function() { + return { + restrict: 'EA', + scope: { + affApi4Ctrl: '=', + affApi4: '@', + affApi4Refresh: '@', + onRefresh: '@' + }, + controllerAs: 'affApi4Ctrl', + controller: function($scope, $parse, crmThrottle, crmApi4) { + var ctrl = this; + + // CONSIDER: Trade-offs of upfront vs ongoing evaluation. + var parts = $parse($scope.affApi4)($scope.$parent); + ctrl.entity = parts[0]; + ctrl.action = parts[1]; + ctrl.params = parts[2]; + ctrl.result = {}; + ctrl.loading = ctrl.firstLoad = true; + + ctrl.refresh = function refresh() { + ctrl.loading = true; + crmThrottle(function () { + return crmApi4(ctrl.entity, ctrl.action, ctrl.params) + .then(function (response) { + ctrl.result = response; + ctrl.loading = ctrl.firstLoad = false; + if ($scope.onRefresh) { + $scope.$parent.$eval($scope.onRefresh, ctrl); + } + }); + }); + }; + + $scope.affApi4Ctrl = this; + + var mode = $scope.affApi4Refresh ? $scope.affApi4Refresh : 'auto'; + switch (mode) { + case 'auto': $scope.$watchCollection('affApi4Ctrl.params', ctrl.refresh); break; + case 'init': ctrl.refresh(); break; + case 'manual': break; + default: throw 'Unrecognized refresh mode: '+ mode; + } + } + }; + }); + +})(angular, CRM.$, CRM._); -- 2.25.1