inputSuggestions.coffee 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. define [
  2. "base"
  3. ], (App) ->
  4. inputSuggestionsController = ($scope, $element, $attrs, Keys) ->
  5. ctrl = @
  6. ctrl.showHint = false
  7. ctrl.hasFocus = false
  8. ctrl.handleFocus = () ->
  9. ctrl.hasFocus = true
  10. ctrl.suggestion = null
  11. ctrl.handleBlur = () ->
  12. ctrl.showHint = false
  13. ctrl.hasFocus = false
  14. ctrl.suggestion = null
  15. ctrl.onBlur()
  16. ctrl.handleKeyDown = ($event) ->
  17. if ($event.which == Keys.TAB or $event.which == Keys.ENTER) and ctrl.suggestion? and ctrl.suggestion != ""
  18. $event.preventDefault()
  19. ctrl.localNgModel += ctrl.suggestion
  20. ctrl.suggestion = null
  21. ctrl.showHint = false
  22. $scope.$watch "$ctrl.localNgModel", (newVal, oldVal) ->
  23. if ctrl.hasFocus and newVal != oldVal
  24. ctrl.suggestion = null
  25. ctrl.showHint = false
  26. ctrl.getSuggestion({ userInput: newVal })
  27. .then (suggestion) ->
  28. if suggestion? and newVal == ctrl.localNgModel
  29. ctrl.showHint = true
  30. ctrl.suggestion = suggestion.replace newVal, ""
  31. .catch () -> ctrl.suggestion = null
  32. return
  33. App.component "inputSuggestions", {
  34. bindings:
  35. localNgModel: "=ngModel"
  36. localNgModelOptions: "=?ngModelOptions"
  37. getSuggestion: "&"
  38. onBlur: "&?"
  39. inputId: "@?"
  40. inputName: "@?"
  41. inputPlaceholder: "@?"
  42. inputType: "@?"
  43. inputRequired: "=?"
  44. controller: inputSuggestionsController
  45. template: [
  46. '<div class="input-suggestions">',
  47. '<div class="form-control input-suggestions-shadow">',
  48. '<span ng-bind="$ctrl.localNgModel"',
  49. ' class="input-suggestions-shadow-existing"',
  50. ' ng-show="$ctrl.showHint">',
  51. '</span>',
  52. '<span ng-bind="$ctrl.suggestion"',
  53. ' class="input-suggestions-shadow-suggested"',
  54. ' ng-show="$ctrl.showHint">',
  55. '</span>',
  56. '</div>',
  57. '<input type="text"',
  58. ' class="form-control input-suggestions-main"',
  59. ' ng-focus="$ctrl.handleFocus()"',
  60. ' ng-keyDown="$ctrl.handleKeyDown($event)"',
  61. ' ng-blur="$ctrl.handleBlur()"',
  62. ' ng-model="$ctrl.localNgModel"',
  63. ' ng-model-options="$ctrl.localNgModelOptions"',
  64. ' ng-model-options="{ debounce: 50 }"',
  65. ' ng-attr-id="{{ ::$ctrl.inputId }}"',
  66. ' ng-attr-placeholder="{{ ::$ctrl.inputPlaceholder }}"',
  67. ' ng-attr-type="{{ ::$ctrl.inputType }}"',
  68. ' ng-attr-name="{{ ::$ctrl.inputName }}"',
  69. ' ng-required="::$ctrl.inputRequired">',
  70. '</div>'
  71. ].join ""
  72. }