templateParamSelector.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. define([
  2. 'angular',
  3. 'app',
  4. 'lodash',
  5. 'jquery',
  6. ],
  7. function (angular, app, _, $) {
  8. 'use strict';
  9. angular
  10. .module('grafana.directives')
  11. .directive('templateParamSelector', function($compile) {
  12. var inputTemplate = '<input type="text" data-provide="typeahead" ' +
  13. ' class="tight-form-clear-input input-medium"' +
  14. ' spellcheck="false" style="display:none"></input>';
  15. var buttonTemplate = '<a class="tight-form-item tabindex="1">{{variable.current.text}} <i class="fa fa-caret-down"></i></a>';
  16. return {
  17. link: function($scope, elem) {
  18. var $input = $(inputTemplate);
  19. var $button = $(buttonTemplate);
  20. var variable = $scope.variable;
  21. $input.appendTo(elem);
  22. $button.appendTo(elem);
  23. function updateVariableValue(value) {
  24. $scope.$apply(function() {
  25. var selected = _.findWhere(variable.options, { text: value });
  26. if (!selected) {
  27. selected = { text: value, value: value };
  28. }
  29. $scope.setVariableValue($scope.variable, selected);
  30. });
  31. }
  32. $input.attr('data-provide', 'typeahead');
  33. $input.typeahead({
  34. minLength: 0,
  35. items: 1000,
  36. updater: function(value) {
  37. $input.val(value);
  38. $input.trigger('blur');
  39. return value;
  40. }
  41. });
  42. var typeahead = $input.data('typeahead');
  43. typeahead.lookup = function () {
  44. var options = _.map(variable.options, function(option) { return option.text; });
  45. this.query = this.$element.val() || '';
  46. return this.process(options);
  47. };
  48. $button.click(function() {
  49. $input.css('width', ($button.width() + 16) + 'px');
  50. $button.hide();
  51. $input.show();
  52. $input.focus();
  53. var typeahead = $input.data('typeahead');
  54. if (typeahead) {
  55. $input.val('');
  56. typeahead.lookup();
  57. }
  58. });
  59. $input.blur(function() {
  60. if ($input.val() !== '') { updateVariableValue($input.val()); }
  61. $input.hide();
  62. $button.show();
  63. $button.focus();
  64. });
  65. $scope.$on('$destroy', function() {
  66. $button.unbind();
  67. typeahead.destroy();
  68. });
  69. $compile(elem.contents())($scope);
  70. }
  71. };
  72. });
  73. });