user_picker.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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()"
  10. </gf-form-dropdown>
  11. </div>
  12. `;
  13. export class UserPickerCtrl {
  14. user: any;
  15. userId: number;
  16. debouncedSearchUsers: any;
  17. /** @ngInject */
  18. constructor(private backendSrv, private $scope, $sce) {
  19. this.user = {text: 'Choose', value: null};
  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.id};
  26. });
  27. }));
  28. }
  29. onChange() {
  30. this.userId = this.user.value;
  31. }
  32. userIdChanged() {
  33. if (this.userId === null) {
  34. this.user = {text: 'Choose', value: null};
  35. }
  36. }
  37. }
  38. export interface User {
  39. id: number;
  40. name: string;
  41. login: string;
  42. email: string;
  43. }
  44. export function userPicker() {
  45. return {
  46. restrict: 'E',
  47. template: template,
  48. controller: UserPickerCtrl,
  49. bindToController: true,
  50. controllerAs: 'ctrl',
  51. scope: {
  52. userId: '=',
  53. },
  54. link: function(scope, elem, attrs, ctrl) {
  55. scope.$watch("ctrl.userId", (newVal, oldVal) => {
  56. ctrl.userIdChanged(newVal);
  57. });
  58. }
  59. };
  60. }
  61. coreModule.directive('userPicker', userPicker);