user_group_picker.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import coreModule from 'app/core/core_module';
  2. import appEvents from 'app/core/app_events';
  3. import _ from 'lodash';
  4. const template = `
  5. <div class="dropdown">
  6. <metric-segment segment="ctrl.userGroupSegment"
  7. get-options="ctrl.debouncedSearchUserGroups($query)"
  8. on-change="ctrl.onChange()"></metric-segment>
  9. </div>
  10. `;
  11. export class UserGroupPickerCtrl {
  12. userGroupSegment: any;
  13. userGroupId: number;
  14. debouncedSearchUserGroups: any;
  15. /** @ngInject */
  16. constructor(private backendSrv, private $scope, $sce, private uiSegmentSrv) {
  17. this.debouncedSearchUserGroups = _.debounce(this.searchUserGroups, 500, {'leading': true, 'trailing': false});
  18. this.resetUserGroupSegment();
  19. }
  20. resetUserGroupSegment() {
  21. this.userGroupId = null;
  22. const userGroupSegment = this.uiSegmentSrv.newSegment({
  23. value: 'Choose',
  24. selectMode: true,
  25. fake: true,
  26. cssClass: 'gf-size-auto'
  27. });
  28. if (!this.userGroupSegment) {
  29. this.userGroupSegment = userGroupSegment;
  30. } else {
  31. this.userGroupSegment.value = userGroupSegment.value;
  32. this.userGroupSegment.html = userGroupSegment.html;
  33. this.userGroupSegment.value = userGroupSegment.value;
  34. }
  35. }
  36. userGroupIdChanged(newVal) {
  37. if (!newVal) {
  38. this.resetUserGroupSegment();
  39. }
  40. }
  41. searchUserGroups(query: string) {
  42. return Promise.resolve(this.backendSrv.get('/api/user-groups/search?perpage=10&page=1&query=' + query).then(result => {
  43. return _.map(result.userGroups, ug => { return this.uiSegmentSrv.newSegment(ug.name); });
  44. }));
  45. }
  46. onChange() {
  47. this.backendSrv.get('/api/user-groups/search?perpage=10&page=1&query=' + this.userGroupSegment.value)
  48. .then(result => {
  49. if (!result) {
  50. return;
  51. }
  52. result.userGroups.forEach(ug => {
  53. if (ug.name === this.userGroupSegment.value) {
  54. this.userGroupId = ug.id;
  55. }
  56. });
  57. });
  58. }
  59. }
  60. export function userGroupPicker() {
  61. return {
  62. restrict: 'E',
  63. template: template,
  64. controller: UserGroupPickerCtrl,
  65. bindToController: true,
  66. controllerAs: 'ctrl',
  67. scope: {
  68. userGroupId: '=',
  69. },
  70. link: function(scope, elem, attrs, ctrl) {
  71. scope.$watch("ctrl.userGroupId", (newVal, oldVal) => {
  72. ctrl.userGroupIdChanged(newVal);
  73. });
  74. }
  75. };
  76. }
  77. coreModule.directive('userGroupPicker', userGroupPicker);