user_picker.ts 1.6 KB

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