user_picker.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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.get('/api/users/search?perpage=10&page=1&query=' + query).then(result => {
  27. return _.map(result.users, user => {
  28. return { text: user.login + ' - ' + user.email, value: user };
  29. });
  30. })
  31. );
  32. }
  33. onChange(option) {
  34. this.userPicked({ $user: option.value });
  35. }
  36. reset() {
  37. this.user = { text: 'Choose', value: null };
  38. }
  39. }
  40. export interface User {
  41. id: number;
  42. name: string;
  43. login: string;
  44. email: string;
  45. }
  46. export function userPicker() {
  47. return {
  48. restrict: 'E',
  49. template: template,
  50. controller: UserPickerCtrl,
  51. bindToController: true,
  52. controllerAs: 'ctrl',
  53. scope: {
  54. userPicked: '&',
  55. },
  56. link: function(scope, elem, attrs, ctrl) {
  57. scope.$on('user-picker-reset', () => {
  58. ctrl.reset();
  59. });
  60. },
  61. };
  62. }
  63. coreModule.directive('userPicker', userPicker);