templateParamSelector.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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="grafana-target-segment-input input-medium"' +
  14. ' spellcheck="false" style="display:none"></input>';
  15. var buttonTemplate = '<a class="grafana-target-segment tabindex="1">{{variable.current.text}}</a>';
  16. return {
  17. link: function($scope, elem) {
  18. var $input = $(inputTemplate);
  19. var $button = $(buttonTemplate);
  20. var variable = $scope.variable;
  21. var options = _.map(variable.options, function(option) {
  22. return option.text;
  23. });
  24. $input.appendTo(elem);
  25. $button.appendTo(elem);
  26. function updateVariableValue(value) {
  27. $scope.$apply(function() {
  28. var selected = _.findWhere(variable.options, { text: value });
  29. if (!selected) {
  30. selected = { text: value, value: value };
  31. }
  32. $scope.setVariableValue($scope.variable, selected);
  33. });
  34. }
  35. $input.attr('data-provide', 'typeahead');
  36. $input.typeahead({
  37. source: options,
  38. minLength: 0,
  39. items: 10,
  40. updater: function(value) {
  41. updateVariableValue(value);
  42. $input.trigger('blur');
  43. return '';
  44. }
  45. });
  46. var typeahead = $input.data('typeahead');
  47. typeahead.lookup = function () {
  48. this.query = this.$element.val() || '';
  49. return this.process(this.source);
  50. };
  51. $button.click(function() {
  52. $input.css('width', ($button.width() + 16) + 'px');
  53. $button.hide();
  54. $input.show();
  55. $input.focus();
  56. var typeahead = $input.data('typeahead');
  57. if (typeahead) {
  58. $input.val('');
  59. typeahead.lookup();
  60. }
  61. });
  62. $input.blur(function() {
  63. if ($input.val() !== '') { updateVariableValue($input.val()); }
  64. $input.hide();
  65. $button.show();
  66. $button.focus();
  67. });
  68. $compile(elem.contents())($scope);
  69. }
  70. };
  71. });
  72. });