autocomplete.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. /*!
  2. * Angular Material Design
  3. * https://github.com/angular/material
  4. * @license MIT
  5. * v0.11.4
  6. */
  7. (function( window, angular, undefined ){
  8. "use strict";
  9. /**
  10. * @ngdoc module
  11. * @name material.components.autocomplete
  12. */
  13. /*
  14. * @see js folder for autocomplete implementation
  15. */
  16. angular.module('material.components.autocomplete', [
  17. 'material.core',
  18. 'material.components.icon',
  19. 'material.components.virtualRepeat'
  20. ]);
  21. angular
  22. .module('material.components.autocomplete')
  23. .controller('MdAutocompleteCtrl', MdAutocompleteCtrl);
  24. var ITEM_HEIGHT = 41,
  25. MAX_HEIGHT = 5.5 * ITEM_HEIGHT,
  26. MENU_PADDING = 8;
  27. function MdAutocompleteCtrl ($scope, $element, $mdUtil, $mdConstant, $mdTheming, $window,
  28. $animate, $rootElement, $attrs, $q) {
  29. //-- private variables
  30. var ctrl = this,
  31. itemParts = $scope.itemsExpr.split(/ in /i),
  32. itemExpr = itemParts[ 1 ],
  33. elements = null,
  34. cache = {},
  35. noBlur = false,
  36. selectedItemWatchers = [],
  37. hasFocus = false,
  38. lastCount = 0;
  39. //-- public variables with handlers
  40. defineProperty('hidden', handleHiddenChange, true);
  41. //-- public variables
  42. ctrl.scope = $scope;
  43. ctrl.parent = $scope.$parent;
  44. ctrl.itemName = itemParts[ 0 ];
  45. ctrl.matches = [];
  46. ctrl.loading = false;
  47. ctrl.hidden = true;
  48. ctrl.index = null;
  49. ctrl.messages = [];
  50. ctrl.id = $mdUtil.nextUid();
  51. ctrl.isDisabled = null;
  52. ctrl.isRequired = null;
  53. ctrl.hasNotFound = false;
  54. //-- public methods
  55. ctrl.keydown = keydown;
  56. ctrl.blur = blur;
  57. ctrl.focus = focus;
  58. ctrl.clear = clearValue;
  59. ctrl.select = select;
  60. ctrl.listEnter = onListEnter;
  61. ctrl.listLeave = onListLeave;
  62. ctrl.mouseUp = onMouseup;
  63. ctrl.getCurrentDisplayValue = getCurrentDisplayValue;
  64. ctrl.registerSelectedItemWatcher = registerSelectedItemWatcher;
  65. ctrl.unregisterSelectedItemWatcher = unregisterSelectedItemWatcher;
  66. ctrl.notFoundVisible = notFoundVisible;
  67. ctrl.loadingIsVisible = loadingIsVisible;
  68. return init();
  69. //-- initialization methods
  70. /**
  71. * Initialize the controller, setup watchers, gather elements
  72. */
  73. function init () {
  74. $mdUtil.initOptionalProperties($scope, $attrs, { searchText: null, selectedItem: null });
  75. $mdTheming($element);
  76. configureWatchers();
  77. $mdUtil.nextTick(function () {
  78. gatherElements();
  79. moveDropdown();
  80. focusElement();
  81. $element.on('focus', focusElement);
  82. });
  83. }
  84. /**
  85. * Calculates the dropdown's position and applies the new styles to the menu element
  86. * @returns {*}
  87. */
  88. function positionDropdown () {
  89. if (!elements) return $mdUtil.nextTick(positionDropdown, false, $scope);
  90. var hrect = elements.wrap.getBoundingClientRect(),
  91. vrect = elements.snap.getBoundingClientRect(),
  92. root = elements.root.getBoundingClientRect(),
  93. top = vrect.bottom - root.top,
  94. bot = root.bottom - vrect.top,
  95. left = hrect.left - root.left,
  96. width = hrect.width,
  97. styles = {
  98. left: left + 'px',
  99. minWidth: width + 'px',
  100. maxWidth: Math.max(hrect.right - root.left, root.right - hrect.left) - MENU_PADDING + 'px'
  101. };
  102. if (top > bot && root.height - hrect.bottom - MENU_PADDING < MAX_HEIGHT) {
  103. styles.top = 'auto';
  104. styles.bottom = bot + 'px';
  105. styles.maxHeight = Math.min(MAX_HEIGHT, hrect.top - root.top - MENU_PADDING) + 'px';
  106. } else {
  107. styles.top = top + 'px';
  108. styles.bottom = 'auto';
  109. styles.maxHeight = Math.min(MAX_HEIGHT, root.bottom - hrect.bottom - MENU_PADDING) + 'px';
  110. }
  111. elements.$.scrollContainer.css(styles);
  112. $mdUtil.nextTick(correctHorizontalAlignment, false);
  113. /**
  114. * Makes sure that the menu doesn't go off of the screen on either side.
  115. */
  116. function correctHorizontalAlignment () {
  117. var dropdown = elements.scrollContainer.getBoundingClientRect(),
  118. styles = {};
  119. if (dropdown.right > root.right - MENU_PADDING) {
  120. styles.left = (hrect.right - dropdown.width) + 'px';
  121. }
  122. elements.$.scrollContainer.css(styles);
  123. }
  124. }
  125. /**
  126. * Moves the dropdown menu to the body tag in order to avoid z-index and overflow issues.
  127. */
  128. function moveDropdown () {
  129. if (!elements.$.root.length) return;
  130. $mdTheming(elements.$.scrollContainer);
  131. elements.$.scrollContainer.detach();
  132. elements.$.root.append(elements.$.scrollContainer);
  133. if ($animate.pin) $animate.pin(elements.$.scrollContainer, $rootElement);
  134. }
  135. /**
  136. * Sends focus to the input element.
  137. */
  138. function focusElement () {
  139. if ($scope.autofocus) elements.input.focus();
  140. }
  141. /**
  142. * Sets up any watchers used by autocomplete
  143. */
  144. function configureWatchers () {
  145. var wait = parseInt($scope.delay, 10) || 0;
  146. $attrs.$observe('disabled', function (value) { ctrl.isDisabled = value; });
  147. $attrs.$observe('required', function (value) { ctrl.isRequired = value !== null; });
  148. $scope.$watch('searchText', wait ? $mdUtil.debounce(handleSearchText, wait) : handleSearchText);
  149. $scope.$watch('selectedItem', selectedItemChange);
  150. angular.element($window).on('resize', positionDropdown);
  151. $scope.$on('$destroy', cleanup);
  152. }
  153. /**
  154. * Removes any events or leftover elements created by this controller
  155. */
  156. function cleanup () {
  157. angular.element($window).off('resize', positionDropdown);
  158. if ( elements ){
  159. var items = 'ul scroller scrollContainer input'.split(' ');
  160. angular.forEach(items, function(key){
  161. elements.$[key].remove();
  162. });
  163. }
  164. }
  165. /**
  166. * Gathers all of the elements needed for this controller
  167. */
  168. function gatherElements () {
  169. elements = {
  170. main: $element[0],
  171. scrollContainer: $element[0].getElementsByClassName('md-virtual-repeat-container')[0],
  172. scroller: $element[0].getElementsByClassName('md-virtual-repeat-scroller')[0],
  173. ul: $element.find('ul')[0],
  174. input: $element.find('input')[0],
  175. wrap: $element.find('md-autocomplete-wrap')[0],
  176. root: document.body
  177. };
  178. elements.li = elements.ul.getElementsByTagName('li');
  179. elements.snap = getSnapTarget();
  180. elements.$ = getAngularElements(elements);
  181. }
  182. /**
  183. * Finds the element that the menu will base its position on
  184. * @returns {*}
  185. */
  186. function getSnapTarget () {
  187. for (var element = $element; element.length; element = element.parent()) {
  188. if (angular.isDefined(element.attr('md-autocomplete-snap'))) return element[ 0 ];
  189. }
  190. return elements.wrap;
  191. }
  192. /**
  193. * Gathers angular-wrapped versions of each element
  194. * @param elements
  195. * @returns {{}}
  196. */
  197. function getAngularElements (elements) {
  198. var obj = {};
  199. for (var key in elements) {
  200. if (elements.hasOwnProperty(key)) obj[ key ] = angular.element(elements[ key ]);
  201. }
  202. return obj;
  203. }
  204. //-- event/change handlers
  205. /**
  206. * Handles changes to the `hidden` property.
  207. * @param hidden
  208. * @param oldHidden
  209. */
  210. function handleHiddenChange (hidden, oldHidden) {
  211. if (!hidden && oldHidden) {
  212. positionDropdown();
  213. if (elements) {
  214. $mdUtil.nextTick(function () {
  215. $mdUtil.disableScrollAround(elements.ul);
  216. }, false, $scope);
  217. }
  218. } else if (hidden && !oldHidden) {
  219. $mdUtil.nextTick(function () {
  220. $mdUtil.enableScrolling();
  221. }, false, $scope);
  222. }
  223. }
  224. /**
  225. * When the user mouses over the dropdown menu, ignore blur events.
  226. */
  227. function onListEnter () {
  228. noBlur = true;
  229. }
  230. /**
  231. * When the user's mouse leaves the menu, blur events may hide the menu again.
  232. */
  233. function onListLeave () {
  234. noBlur = false;
  235. ctrl.hidden = shouldHide();
  236. }
  237. /**
  238. * When the mouse button is released, send focus back to the input field.
  239. */
  240. function onMouseup () {
  241. elements.input.focus();
  242. }
  243. /**
  244. * Handles changes to the selected item.
  245. * @param selectedItem
  246. * @param previousSelectedItem
  247. */
  248. function selectedItemChange (selectedItem, previousSelectedItem) {
  249. if (selectedItem) {
  250. getDisplayValue(selectedItem).then(function (val) {
  251. $scope.searchText = val;
  252. handleSelectedItemChange(selectedItem, previousSelectedItem);
  253. });
  254. }
  255. if (selectedItem !== previousSelectedItem) announceItemChange();
  256. }
  257. /**
  258. * Use the user-defined expression to announce changes each time a new item is selected
  259. */
  260. function announceItemChange () {
  261. angular.isFunction($scope.itemChange) && $scope.itemChange(getItemAsNameVal($scope.selectedItem));
  262. }
  263. /**
  264. * Use the user-defined expression to announce changes each time the search text is changed
  265. */
  266. function announceTextChange () {
  267. angular.isFunction($scope.textChange) && $scope.textChange();
  268. }
  269. /**
  270. * Calls any external watchers listening for the selected item. Used in conjunction with
  271. * `registerSelectedItemWatcher`.
  272. * @param selectedItem
  273. * @param previousSelectedItem
  274. */
  275. function handleSelectedItemChange (selectedItem, previousSelectedItem) {
  276. selectedItemWatchers.forEach(function (watcher) { watcher(selectedItem, previousSelectedItem); });
  277. }
  278. /**
  279. * Register a function to be called when the selected item changes.
  280. * @param cb
  281. */
  282. function registerSelectedItemWatcher (cb) {
  283. if (selectedItemWatchers.indexOf(cb) == -1) {
  284. selectedItemWatchers.push(cb);
  285. }
  286. }
  287. /**
  288. * Unregister a function previously registered for selected item changes.
  289. * @param cb
  290. */
  291. function unregisterSelectedItemWatcher (cb) {
  292. var i = selectedItemWatchers.indexOf(cb);
  293. if (i != -1) {
  294. selectedItemWatchers.splice(i, 1);
  295. }
  296. }
  297. /**
  298. * Handles changes to the searchText property.
  299. * @param searchText
  300. * @param previousSearchText
  301. */
  302. function handleSearchText (searchText, previousSearchText) {
  303. ctrl.index = getDefaultIndex();
  304. // do nothing on init
  305. if (searchText === previousSearchText) return;
  306. getDisplayValue($scope.selectedItem).then(function (val) {
  307. // clear selected item if search text no longer matches it
  308. if (searchText !== val) {
  309. $scope.selectedItem = null;
  310. // trigger change event if available
  311. if (searchText !== previousSearchText) announceTextChange();
  312. // cancel results if search text is not long enough
  313. if (!isMinLengthMet()) {
  314. ctrl.matches = [];
  315. setLoading(false);
  316. updateMessages();
  317. } else {
  318. handleQuery();
  319. }
  320. }
  321. });
  322. }
  323. /**
  324. * Handles input blur event, determines if the dropdown should hide.
  325. */
  326. function blur () {
  327. if (!noBlur) {
  328. hasFocus = false;
  329. ctrl.hidden = shouldHide();
  330. }
  331. }
  332. function doBlur(forceBlur) {
  333. if (forceBlur) {
  334. noBlur = false;
  335. }
  336. elements.input.blur();
  337. }
  338. /**
  339. * Handles input focus event, determines if the dropdown should show.
  340. */
  341. function focus () {
  342. hasFocus = true;
  343. //-- if searchText is null, let's force it to be a string
  344. if (!angular.isString($scope.searchText)) $scope.searchText = '';
  345. ctrl.hidden = shouldHide();
  346. if (!ctrl.hidden) handleQuery();
  347. }
  348. /**
  349. * Handles keyboard input.
  350. * @param event
  351. */
  352. function keydown (event) {
  353. switch (event.keyCode) {
  354. case $mdConstant.KEY_CODE.DOWN_ARROW:
  355. if (ctrl.loading) return;
  356. event.stopPropagation();
  357. event.preventDefault();
  358. ctrl.index = Math.min(ctrl.index + 1, ctrl.matches.length - 1);
  359. updateScroll();
  360. updateMessages();
  361. break;
  362. case $mdConstant.KEY_CODE.UP_ARROW:
  363. if (ctrl.loading) return;
  364. event.stopPropagation();
  365. event.preventDefault();
  366. ctrl.index = ctrl.index < 0 ? ctrl.matches.length - 1 : Math.max(0, ctrl.index - 1);
  367. updateScroll();
  368. updateMessages();
  369. break;
  370. case $mdConstant.KEY_CODE.TAB:
  371. case $mdConstant.KEY_CODE.ENTER:
  372. if (ctrl.hidden || ctrl.loading || ctrl.index < 0 || ctrl.matches.length < 1) return;
  373. event.stopPropagation();
  374. event.preventDefault();
  375. select(ctrl.index);
  376. break;
  377. case $mdConstant.KEY_CODE.ESCAPE:
  378. event.stopPropagation();
  379. event.preventDefault();
  380. clearValue();
  381. // Force the component to blur if they hit escape
  382. doBlur(true);
  383. break;
  384. default:
  385. }
  386. }
  387. //-- getters
  388. /**
  389. * Returns the minimum length needed to display the dropdown.
  390. * @returns {*}
  391. */
  392. function getMinLength () {
  393. return angular.isNumber($scope.minLength) ? $scope.minLength : 1;
  394. }
  395. /**
  396. * Returns the display value for an item.
  397. * @param item
  398. * @returns {*}
  399. */
  400. function getDisplayValue (item) {
  401. return $q.when(getItemText(item) || item);
  402. /**
  403. * Getter function to invoke user-defined expression (in the directive)
  404. * to convert your object to a single string.
  405. */
  406. function getItemText (item) {
  407. return (item && $scope.itemText) ? $scope.itemText(getItemAsNameVal(item)) : null;
  408. }
  409. }
  410. /**
  411. * Returns the locals object for compiling item templates.
  412. * @param item
  413. * @returns {{}}
  414. */
  415. function getItemAsNameVal (item) {
  416. if (!item) return undefined;
  417. var locals = {};
  418. if (ctrl.itemName) locals[ ctrl.itemName ] = item;
  419. return locals;
  420. }
  421. /**
  422. * Returns the default index based on whether or not autoselect is enabled.
  423. * @returns {number}
  424. */
  425. function getDefaultIndex () {
  426. return $scope.autoselect ? 0 : -1;
  427. }
  428. /**
  429. * Sets the loading parameter and updates the hidden state.
  430. * @param value {boolean} Whether or not the component is currently loading.
  431. */
  432. function setLoading(value) {
  433. if (ctrl.loading != value) {
  434. ctrl.loading = value;
  435. }
  436. // Always refresh the hidden variable as something else might have changed
  437. ctrl.hidden = shouldHide();
  438. }
  439. /**
  440. * Determines if the menu should be hidden.
  441. * @returns {boolean}
  442. */
  443. function shouldHide () {
  444. if ((ctrl.loading && !hasMatches()) || hasSelection() || !hasFocus) {
  445. return true;
  446. }
  447. return !shouldShow();
  448. }
  449. /**
  450. * Determines if the menu should be shown.
  451. * @returns {boolean}
  452. */
  453. function shouldShow() {
  454. return (isMinLengthMet() && hasMatches()) || notFoundVisible();
  455. }
  456. /**
  457. * Returns true if the search text has matches.
  458. * @returns {boolean}
  459. */
  460. function hasMatches() {
  461. return ctrl.matches.length ? true : false;
  462. }
  463. /**
  464. * Returns true if the autocomplete has a valid selection.
  465. * @returns {boolean}
  466. */
  467. function hasSelection() {
  468. return ctrl.scope.selectedItem ? true : false;
  469. }
  470. /**
  471. * Returns true if the loading indicator is, or should be, visible.
  472. * @returns {boolean}
  473. */
  474. function loadingIsVisible() {
  475. return ctrl.loading && !hasSelection();
  476. }
  477. /**
  478. * Returns the display value of the current item.
  479. * @returns {*}
  480. */
  481. function getCurrentDisplayValue () {
  482. return getDisplayValue(ctrl.matches[ ctrl.index ]);
  483. }
  484. /**
  485. * Determines if the minimum length is met by the search text.
  486. * @returns {*}
  487. */
  488. function isMinLengthMet () {
  489. return ($scope.searchText || '').length >= getMinLength();
  490. }
  491. //-- actions
  492. /**
  493. * Defines a public property with a handler and a default value.
  494. * @param key
  495. * @param handler
  496. * @param value
  497. */
  498. function defineProperty (key, handler, value) {
  499. Object.defineProperty(ctrl, key, {
  500. get: function () { return value; },
  501. set: function (newValue) {
  502. var oldValue = value;
  503. value = newValue;
  504. handler(newValue, oldValue);
  505. }
  506. });
  507. }
  508. /**
  509. * Selects the item at the given index.
  510. * @param index
  511. */
  512. function select (index) {
  513. //-- force form to update state for validation
  514. $mdUtil.nextTick(function () {
  515. getDisplayValue(ctrl.matches[ index ]).then(function (val) {
  516. var ngModel = elements.$.input.controller('ngModel');
  517. ngModel.$setViewValue(val);
  518. ngModel.$render();
  519. }).finally(function () {
  520. $scope.selectedItem = ctrl.matches[ index ];
  521. setLoading(false);
  522. });
  523. }, false);
  524. }
  525. /**
  526. * Clears the searchText value and selected item.
  527. */
  528. function clearValue () {
  529. // Set the loading to true so we don't see flashes of content
  530. setLoading(true);
  531. // Reset our variables
  532. ctrl.index = 0;
  533. ctrl.matches = [];
  534. $scope.searchText = '';
  535. // Tell the select to fire and select nothing
  536. select(-1);
  537. // Per http://www.w3schools.com/jsref/event_oninput.asp
  538. var eventObj = document.createEvent('CustomEvent');
  539. eventObj.initCustomEvent('input', true, true, { value: $scope.searchText });
  540. elements.input.dispatchEvent(eventObj);
  541. elements.input.focus();
  542. }
  543. /**
  544. * Fetches the results for the provided search text.
  545. * @param searchText
  546. */
  547. function fetchResults (searchText) {
  548. var items = $scope.$parent.$eval(itemExpr),
  549. term = searchText.toLowerCase();
  550. if (angular.isArray(items)) {
  551. handleResults(items);
  552. } else if (items) {
  553. setLoading(true);
  554. $mdUtil.nextTick(function () {
  555. if (items.success) items.success(handleResults);
  556. if (items.then) items.then(handleResults);
  557. if (items.finally) items.finally(function () {
  558. setLoading(false);
  559. });
  560. },true, $scope);
  561. }
  562. function handleResults (matches) {
  563. cache[ term ] = matches;
  564. if ((searchText || '') !== ($scope.searchText || '')) return; //-- just cache the results if old request
  565. ctrl.matches = matches;
  566. ctrl.hidden = shouldHide();
  567. if ($scope.selectOnMatch) selectItemOnMatch();
  568. updateMessages();
  569. positionDropdown();
  570. }
  571. }
  572. /**
  573. * Updates the ARIA messages
  574. */
  575. function updateMessages () {
  576. getCurrentDisplayValue().then(function (msg) {
  577. ctrl.messages = [ getCountMessage(), msg ];
  578. });
  579. }
  580. /**
  581. * Returns the ARIA message for how many results match the current query.
  582. * @returns {*}
  583. */
  584. function getCountMessage () {
  585. if (lastCount === ctrl.matches.length) return '';
  586. lastCount = ctrl.matches.length;
  587. switch (ctrl.matches.length) {
  588. case 0:
  589. return 'There are no matches available.';
  590. case 1:
  591. return 'There is 1 match available.';
  592. default:
  593. return 'There are ' + ctrl.matches.length + ' matches available.';
  594. }
  595. }
  596. /**
  597. * Makes sure that the focused element is within view.
  598. */
  599. function updateScroll () {
  600. if (!elements.li[0]) return;
  601. var height = elements.li[0].offsetHeight,
  602. top = height * ctrl.index,
  603. bot = top + height,
  604. hgt = elements.scroller.clientHeight,
  605. scrollTop = elements.scroller.scrollTop;
  606. if (top < scrollTop) {
  607. scrollTo(top);
  608. } else if (bot > scrollTop + hgt) {
  609. scrollTo(bot - hgt);
  610. }
  611. }
  612. function scrollTo (offset) {
  613. elements.$.scrollContainer.controller('mdVirtualRepeatContainer').scrollTo(offset);
  614. }
  615. function notFoundVisible () {
  616. var textLength = (ctrl.scope.searchText || '').length;
  617. return ctrl.hasNotFound && !hasMatches() && !ctrl.loading && textLength >= getMinLength() && hasFocus && !hasSelection();
  618. }
  619. /**
  620. * Starts the query to gather the results for the current searchText. Attempts to return cached
  621. * results first, then forwards the process to `fetchResults` if necessary.
  622. */
  623. function handleQuery () {
  624. var searchText = $scope.searchText,
  625. term = searchText.toLowerCase();
  626. //-- if results are cached, pull in cached results
  627. if (!$scope.noCache && cache[ term ]) {
  628. ctrl.matches = cache[ term ];
  629. updateMessages();
  630. } else {
  631. fetchResults(searchText);
  632. }
  633. ctrl.hidden = shouldHide();
  634. }
  635. /**
  636. * If there is only one matching item and the search text matches its display value exactly,
  637. * automatically select that item. Note: This function is only called if the user uses the
  638. * `md-select-on-match` flag.
  639. */
  640. function selectItemOnMatch () {
  641. var searchText = $scope.searchText,
  642. matches = ctrl.matches,
  643. item = matches[ 0 ];
  644. if (matches.length === 1) getDisplayValue(item).then(function (displayValue) {
  645. if (searchText == displayValue) select(0);
  646. });
  647. }
  648. }
  649. MdAutocompleteCtrl.$inject = ["$scope", "$element", "$mdUtil", "$mdConstant", "$mdTheming", "$window", "$animate", "$rootElement", "$attrs", "$q"];
  650. angular
  651. .module('material.components.autocomplete')
  652. .directive('mdAutocomplete', MdAutocomplete);
  653. /**
  654. * @ngdoc directive
  655. * @name mdAutocomplete
  656. * @module material.components.autocomplete
  657. *
  658. * @description
  659. * `<md-autocomplete>` is a special input component with a drop-down of all possible matches to a
  660. * custom query. This component allows you to provide real-time suggestions as the user types
  661. * in the input area.
  662. *
  663. * To start, you will need to specify the required parameters and provide a template for your
  664. * results. The content inside `md-autocomplete` will be treated as a template.
  665. *
  666. * In more complex cases, you may want to include other content such as a message to display when
  667. * no matches were found. You can do this by wrapping your template in `md-item-template` and
  668. * adding a tag for `md-not-found`. An example of this is shown below.
  669. *
  670. * ### Validation
  671. *
  672. * You can use `ng-messages` to include validation the same way that you would normally validate;
  673. * however, if you want to replicate a standard input with a floating label, you will have to
  674. * do the following:
  675. *
  676. * - Make sure that your template is wrapped in `md-item-template`
  677. * - Add your `ng-messages` code inside of `md-autocomplete`
  678. * - Add your validation properties to `md-autocomplete` (ie. `required`)
  679. * - Add a `name` to `md-autocomplete` (to be used on the generated `input`)
  680. *
  681. * There is an example below of how this should look.
  682. *
  683. *
  684. * @param {expression} md-items An expression in the format of `item in items` to iterate over
  685. * matches for your search.
  686. * @param {expression=} md-selected-item-change An expression to be run each time a new item is
  687. * selected
  688. * @param {expression=} md-search-text-change An expression to be run each time the search text
  689. * updates
  690. * @param {expression=} md-search-text A model to bind the search query text to
  691. * @param {object=} md-selected-item A model to bind the selected item to
  692. * @param {expression=} md-item-text An expression that will convert your object to a single string.
  693. * @param {string=} placeholder Placeholder text that will be forwarded to the input.
  694. * @param {boolean=} md-no-cache Disables the internal caching that happens in autocomplete
  695. * @param {boolean=} ng-disabled Determines whether or not to disable the input field
  696. * @param {number=} md-min-length Specifies the minimum length of text before autocomplete will
  697. * make suggestions
  698. * @param {number=} md-delay Specifies the amount of time (in milliseconds) to wait before looking
  699. * for results
  700. * @param {boolean=} md-autofocus If true, will immediately focus the input element
  701. * @param {boolean=} md-autoselect If true, the first item will be selected by default
  702. * @param {string=} md-menu-class This will be applied to the dropdown menu for styling
  703. * @param {string=} md-floating-label This will add a floating label to autocomplete and wrap it in
  704. * `md-input-container`
  705. * @param {string=} md-input-name The name attribute given to the input element to be used with
  706. * FormController
  707. * @param {string=} md-input-id An ID to be added to the input element
  708. * @param {number=} md-input-minlength The minimum length for the input's value for validation
  709. * @param {number=} md-input-maxlength The maximum length for the input's value for validation
  710. * @param {boolean=} md-select-on-match When set, autocomplete will automatically select exact
  711. * the item if the search text is an exact match
  712. *
  713. * @usage
  714. * ### Basic Example
  715. * <hljs lang="html">
  716. * <md-autocomplete
  717. * md-selected-item="selectedItem"
  718. * md-search-text="searchText"
  719. * md-items="item in getMatches(searchText)"
  720. * md-item-text="item.display">
  721. * <span md-highlight-text="searchText">{{item.display}}</span>
  722. * </md-autocomplete>
  723. * </hljs>
  724. *
  725. * ### Example with "not found" message
  726. * <hljs lang="html">
  727. * <md-autocomplete
  728. * md-selected-item="selectedItem"
  729. * md-search-text="searchText"
  730. * md-items="item in getMatches(searchText)"
  731. * md-item-text="item.display">
  732. * <md-item-template>
  733. * <span md-highlight-text="searchText">{{item.display}}</span>
  734. * </md-item-template>
  735. * <md-not-found>
  736. * No matches found.
  737. * </md-not-found>
  738. * </md-autocomplete>
  739. * </hljs>
  740. *
  741. * In this example, our code utilizes `md-item-template` and `md-not-found` to specify the
  742. * different parts that make up our component.
  743. *
  744. * ### Example with validation
  745. * <hljs lang="html">
  746. * <form name="autocompleteForm">
  747. * <md-autocomplete
  748. * required
  749. * md-input-name="autocomplete"
  750. * md-selected-item="selectedItem"
  751. * md-search-text="searchText"
  752. * md-items="item in getMatches(searchText)"
  753. * md-item-text="item.display">
  754. * <md-item-template>
  755. * <span md-highlight-text="searchText">{{item.display}}</span>
  756. * </md-item-template>
  757. * <div ng-messages="autocompleteForm.autocomplete.$error">
  758. * <div ng-message="required">This field is required</div>
  759. * </div>
  760. * </md-autocomplete>
  761. * </form>
  762. * </hljs>
  763. *
  764. * In this example, our code utilizes `md-item-template` and `md-not-found` to specify the
  765. * different parts that make up our component.
  766. */
  767. function MdAutocomplete () {
  768. var hasNotFoundTemplate = false;
  769. return {
  770. controller: 'MdAutocompleteCtrl',
  771. controllerAs: '$mdAutocompleteCtrl',
  772. scope: {
  773. inputName: '@mdInputName',
  774. inputMinlength: '@mdInputMinlength',
  775. inputMaxlength: '@mdInputMaxlength',
  776. searchText: '=?mdSearchText',
  777. selectedItem: '=?mdSelectedItem',
  778. itemsExpr: '@mdItems',
  779. itemText: '&mdItemText',
  780. placeholder: '@placeholder',
  781. noCache: '=?mdNoCache',
  782. selectOnMatch: '=?mdSelectOnMatch',
  783. itemChange: '&?mdSelectedItemChange',
  784. textChange: '&?mdSearchTextChange',
  785. minLength: '=?mdMinLength',
  786. delay: '=?mdDelay',
  787. autofocus: '=?mdAutofocus',
  788. floatingLabel: '@?mdFloatingLabel',
  789. autoselect: '=?mdAutoselect',
  790. menuClass: '@?mdMenuClass',
  791. inputId: '@?mdInputId'
  792. },
  793. link: function(scope, element, attrs, controller) {
  794. controller.hasNotFound = hasNotFoundTemplate;
  795. },
  796. template: function (element, attr) {
  797. var noItemsTemplate = getNoItemsTemplate(),
  798. itemTemplate = getItemTemplate(),
  799. leftover = element.html(),
  800. tabindex = attr.tabindex;
  801. if (noItemsTemplate) {
  802. hasNotFoundTemplate = true;
  803. }
  804. if (attr.hasOwnProperty('tabindex')) {
  805. element.attr('tabindex', '-1');
  806. }
  807. return '\
  808. <md-autocomplete-wrap\
  809. layout="row"\
  810. ng-class="{ \'md-whiteframe-z1\': !floatingLabel, \'md-menu-showing\': !$mdAutocompleteCtrl.hidden }"\
  811. role="listbox">\
  812. ' + getInputElement() + '\
  813. <md-progress-linear\
  814. ng-if="$mdAutocompleteCtrl.loadingIsVisible()"\
  815. md-mode="indeterminate"></md-progress-linear>\
  816. <md-virtual-repeat-container\
  817. md-auto-shrink\
  818. md-auto-shrink-min="1"\
  819. ng-hide="$mdAutocompleteCtrl.hidden"\
  820. class="md-autocomplete-suggestions-container md-whiteframe-z1"\
  821. role="presentation">\
  822. <ul class="md-autocomplete-suggestions"\
  823. ng-class="::menuClass"\
  824. id="ul-{{$mdAutocompleteCtrl.id}}"\
  825. ng-mouseenter="$mdAutocompleteCtrl.listEnter()"\
  826. ng-mouseleave="$mdAutocompleteCtrl.listLeave()"\
  827. ng-mouseup="$mdAutocompleteCtrl.mouseUp()">\
  828. <li md-virtual-repeat="item in $mdAutocompleteCtrl.matches"\
  829. ng-class="{ selected: $index === $mdAutocompleteCtrl.index }"\
  830. ng-click="$mdAutocompleteCtrl.select($index)"\
  831. md-extra-name="$mdAutocompleteCtrl.itemName">\
  832. ' + itemTemplate + '\
  833. </li>' + noItemsTemplate + '\
  834. </ul>\
  835. </md-virtual-repeat-container>\
  836. </md-autocomplete-wrap>\
  837. <aria-status\
  838. class="md-visually-hidden"\
  839. role="status"\
  840. aria-live="assertive">\
  841. <p ng-repeat="message in $mdAutocompleteCtrl.messages track by $index" ng-if="message">{{message}}</p>\
  842. </aria-status>';
  843. function getItemTemplate() {
  844. var templateTag = element.find('md-item-template').detach(),
  845. html = templateTag.length ? templateTag.html() : element.html();
  846. if (!templateTag.length) element.empty();
  847. return '<md-autocomplete-parent-scope md-autocomplete-replace>' + html + '</md-autocomplete-parent-scope>';
  848. }
  849. function getNoItemsTemplate() {
  850. var templateTag = element.find('md-not-found').detach(),
  851. template = templateTag.length ? templateTag.html() : '';
  852. return template
  853. ? '<li ng-if="$mdAutocompleteCtrl.notFoundVisible()"\
  854. md-autocomplete-parent-scope>' + template + '</li>'
  855. : '';
  856. }
  857. function getInputElement () {
  858. if (attr.mdFloatingLabel) {
  859. return '\
  860. <md-input-container flex ng-if="floatingLabel">\
  861. <label>{{floatingLabel}}</label>\
  862. <input type="search"\
  863. ' + (tabindex != null ? 'tabindex="' + tabindex + '"' : '') + '\
  864. id="{{ inputId || \'fl-input-\' + $mdAutocompleteCtrl.id }}"\
  865. name="{{inputName}}"\
  866. autocomplete="off"\
  867. ng-required="$mdAutocompleteCtrl.isRequired"\
  868. ng-minlength="inputMinlength"\
  869. ng-maxlength="inputMaxlength"\
  870. ng-disabled="$mdAutocompleteCtrl.isDisabled"\
  871. ng-model="$mdAutocompleteCtrl.scope.searchText"\
  872. ng-keydown="$mdAutocompleteCtrl.keydown($event)"\
  873. ng-blur="$mdAutocompleteCtrl.blur()"\
  874. ng-focus="$mdAutocompleteCtrl.focus()"\
  875. aria-owns="ul-{{$mdAutocompleteCtrl.id}}"\
  876. aria-label="{{floatingLabel}}"\
  877. aria-autocomplete="list"\
  878. aria-haspopup="true"\
  879. aria-activedescendant=""\
  880. aria-expanded="{{!$mdAutocompleteCtrl.hidden}}"/>\
  881. <div md-autocomplete-parent-scope md-autocomplete-replace>' + leftover + '</div>\
  882. </md-input-container>';
  883. } else {
  884. return '\
  885. <input flex type="search"\
  886. ' + (tabindex != null ? 'tabindex="' + tabindex + '"' : '') + '\
  887. id="{{ inputId || \'input-\' + $mdAutocompleteCtrl.id }}"\
  888. name="{{inputName}}"\
  889. ng-if="!floatingLabel"\
  890. autocomplete="off"\
  891. ng-required="$mdAutocompleteCtrl.isRequired"\
  892. ng-disabled="$mdAutocompleteCtrl.isDisabled"\
  893. ng-model="$mdAutocompleteCtrl.scope.searchText"\
  894. ng-keydown="$mdAutocompleteCtrl.keydown($event)"\
  895. ng-blur="$mdAutocompleteCtrl.blur()"\
  896. ng-focus="$mdAutocompleteCtrl.focus()"\
  897. placeholder="{{placeholder}}"\
  898. aria-owns="ul-{{$mdAutocompleteCtrl.id}}"\
  899. aria-label="{{placeholder}}"\
  900. aria-autocomplete="list"\
  901. aria-haspopup="true"\
  902. aria-activedescendant=""\
  903. aria-expanded="{{!$mdAutocompleteCtrl.hidden}}"/>\
  904. <button\
  905. type="button"\
  906. tabindex="-1"\
  907. ng-if="$mdAutocompleteCtrl.scope.searchText && !$mdAutocompleteCtrl.isDisabled"\
  908. ng-click="$mdAutocompleteCtrl.clear()">\
  909. <md-icon md-svg-icon="md-close"></md-icon>\
  910. <span class="md-visually-hidden">Clear</span>\
  911. </button>\
  912. ';
  913. }
  914. }
  915. }
  916. };
  917. }
  918. angular
  919. .module('material.components.autocomplete')
  920. .directive('mdAutocompleteParentScope', MdAutocompleteItemScopeDirective);
  921. function MdAutocompleteItemScopeDirective($compile, $mdUtil) {
  922. return {
  923. restrict: 'AE',
  924. link: postLink,
  925. terminal: true
  926. };
  927. function postLink(scope, element, attr) {
  928. var ctrl = scope.$mdAutocompleteCtrl;
  929. var newScope = ctrl.parent.$new();
  930. var itemName = ctrl.itemName;
  931. // Watch for changes to our scope's variables and copy them to the new scope
  932. watchVariable('$index', '$index');
  933. watchVariable('item', itemName);
  934. // Recompile the contents with the new/modified scope
  935. $compile(element.contents())(newScope);
  936. // Replace it if required
  937. if (attr.hasOwnProperty('mdAutocompleteReplace')) {
  938. element.after(element.contents());
  939. element.remove();
  940. }
  941. /**
  942. * Creates a watcher for variables that are copied from the parent scope
  943. * @param variable
  944. * @param alias
  945. */
  946. function watchVariable(variable, alias) {
  947. newScope[alias] = scope[variable];
  948. scope.$watch(variable, function(value) {
  949. $mdUtil.nextTick(function() {
  950. newScope[alias] = value;
  951. });
  952. });
  953. }
  954. }
  955. }
  956. MdAutocompleteItemScopeDirective.$inject = ["$compile", "$mdUtil"];
  957. angular
  958. .module('material.components.autocomplete')
  959. .controller('MdHighlightCtrl', MdHighlightCtrl);
  960. function MdHighlightCtrl ($scope, $element, $attrs) {
  961. this.init = init;
  962. function init (termExpr, unsafeTextExpr) {
  963. var text = null,
  964. regex = null,
  965. flags = $attrs.mdHighlightFlags || '',
  966. watcher = $scope.$watch(function($scope) {
  967. return {
  968. term: termExpr($scope),
  969. unsafeText: unsafeTextExpr($scope)
  970. };
  971. }, function (state, prevState) {
  972. if (text === null || state.unsafeText !== prevState.unsafeText) {
  973. text = angular.element('<div>').text(state.unsafeText).html()
  974. }
  975. if (regex === null || state.term !== prevState.term) {
  976. regex = getRegExp(state.term, flags);
  977. }
  978. $element.html(text.replace(regex, '<span class="highlight">$&</span>'));
  979. }, true);
  980. $element.on('$destroy', function () { watcher(); });
  981. }
  982. function sanitize (term) {
  983. return term && term.replace(/[\\\^\$\*\+\?\.\(\)\|\{}\[\]]/g, '\\$&');
  984. }
  985. function getRegExp (text, flags) {
  986. var str = '';
  987. if (flags.indexOf('^') >= 1) str += '^';
  988. str += text;
  989. if (flags.indexOf('$') >= 1) str += '$';
  990. return new RegExp(sanitize(str), flags.replace(/[\$\^]/g, ''));
  991. }
  992. }
  993. MdHighlightCtrl.$inject = ["$scope", "$element", "$attrs"];
  994. angular
  995. .module('material.components.autocomplete')
  996. .directive('mdHighlightText', MdHighlight);
  997. /**
  998. * @ngdoc directive
  999. * @name mdHighlightText
  1000. * @module material.components.autocomplete
  1001. *
  1002. * @description
  1003. * The `md-highlight-text` directive allows you to specify text that should be highlighted within
  1004. * an element. Highlighted text will be wrapped in `<span class="highlight"></span>` which can
  1005. * be styled through CSS. Please note that child elements may not be used with this directive.
  1006. *
  1007. * @param {string} md-highlight-text A model to be searched for
  1008. * @param {string=} md-highlight-flags A list of flags (loosely based on JavaScript RexExp flags).
  1009. * #### **Supported flags**:
  1010. * - `g`: Find all matches within the provided text
  1011. * - `i`: Ignore case when searching for matches
  1012. * - `$`: Only match if the text ends with the search term
  1013. * - `^`: Only match if the text begins with the search term
  1014. *
  1015. * @usage
  1016. * <hljs lang="html">
  1017. * <input placeholder="Enter a search term..." ng-model="searchTerm" type="text" />
  1018. * <ul>
  1019. * <li ng-repeat="result in results" md-highlight-text="searchTerm">
  1020. * {{result.text}}
  1021. * </li>
  1022. * </ul>
  1023. * </hljs>
  1024. */
  1025. function MdHighlight ($interpolate, $parse) {
  1026. return {
  1027. terminal: true,
  1028. controller: 'MdHighlightCtrl',
  1029. compile: function mdHighlightCompile(tElement, tAttr) {
  1030. var termExpr = $parse(tAttr.mdHighlightText);
  1031. var unsafeTextExpr = $interpolate(tElement.html());
  1032. return function mdHighlightLink(scope, element, attr, ctrl) {
  1033. ctrl.init(termExpr, unsafeTextExpr);
  1034. };
  1035. }
  1036. };
  1037. }
  1038. MdHighlight.$inject = ["$interpolate", "$parse"];
  1039. })(window, window.angular);