user_picker.ts 1.5 KB

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