user_picker.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import coreModule from 'app/core/core_module';
  2. import _ from 'lodash';
  3. const template = `
  4. <div class="dropdown">
  5. <gf-form-dropdown model="ctrl.user"
  6. get-options="ctrl.debouncedSearchUsers($query)"
  7. css-class="gf-size-auto"
  8. on-change="ctrl.onChange($option)"
  9. </gf-form-dropdown>
  10. </div>
  11. `;
  12. export class UserPickerCtrl {
  13. user: any;
  14. debouncedSearchUsers: any;
  15. userPicked: any;
  16. /** @ngInject */
  17. constructor(private backendSrv) {
  18. this.reset();
  19. this.debouncedSearchUsers = _.debounce(this.searchUsers, 500, {
  20. leading: true,
  21. trailing: false,
  22. });
  23. }
  24. searchUsers(query: string) {
  25. return Promise.resolve(
  26. this.backendSrv
  27. .get('/api/users/search?perpage=10&page=1&query=' + query)
  28. .then(result => {
  29. return _.map(result.users, user => {
  30. return { text: user.login + ' - ' + user.email, value: user };
  31. });
  32. })
  33. );
  34. }
  35. onChange(option) {
  36. this.userPicked({ $user: option.value });
  37. }
  38. reset() {
  39. this.user = { text: 'Choose', value: null };
  40. }
  41. }
  42. export interface User {
  43. id: number;
  44. name: string;
  45. login: string;
  46. email: string;
  47. }
  48. export function userPicker() {
  49. return {
  50. restrict: 'E',
  51. template: template,
  52. controller: UserPickerCtrl,
  53. bindToController: true,
  54. controllerAs: 'ctrl',
  55. scope: {
  56. userPicked: '&',
  57. },
  58. link: function(scope, elem, attrs, ctrl) {
  59. scope.$on('user-picker-reset', () => {
  60. ctrl.reset();
  61. });
  62. },
  63. };
  64. }
  65. coreModule.directive('userPicker', userPicker);