2 * Angular Material Design
3 * https://github.com/angular/material
7 (function( window, angular, undefined ){
12 * @name material.components.autocomplete
15 * @see js folder for autocomplete implementation
17 angular.module('material.components.autocomplete', [
19 'material.components.icon',
20 'material.components.virtualRepeat'
24 MdAutocompleteCtrl['$inject'] = ["$scope", "$element", "$mdUtil", "$mdConstant", "$mdTheming", "$window", "$animate", "$rootElement", "$attrs", "$q", "$log", "$mdLiveAnnouncer"];angular
25 .module('material.components.autocomplete')
26 .controller('MdAutocompleteCtrl', MdAutocompleteCtrl);
31 INPUT_PADDING = 2; // Padding provided by `md-input-container`
33 function MdAutocompleteCtrl ($scope, $element, $mdUtil, $mdConstant, $mdTheming, $window,
34 $animate, $rootElement, $attrs, $q, $log, $mdLiveAnnouncer) {
36 // Internal Variables.
38 itemParts = $scope.itemsExpr.split(/ in /i),
39 itemExpr = itemParts[ 1 ],
43 selectedItemWatchers = [],
45 fetchesInProgress = 0,
46 enableWrapScroll = null,
47 inputModelCtrl = null,
48 debouncedOnResize = $mdUtil.debounce(onWindowResize);
50 // Public Exported Variables with handlers
51 defineProperty('hidden', handleHiddenChange, true);
53 // Public Exported Variables
55 ctrl.parent = $scope.$parent;
56 ctrl.itemName = itemParts[ 0 ];
61 ctrl.id = $mdUtil.nextUid();
62 ctrl.isDisabled = null;
63 ctrl.isRequired = null;
64 ctrl.isReadonly = null;
65 ctrl.hasNotFound = false;
67 // Public Exported Methods
68 ctrl.keydown = keydown;
71 ctrl.clear = clearValue;
73 ctrl.listEnter = onListEnter;
74 ctrl.listLeave = onListLeave;
75 ctrl.mouseUp = onMouseup;
76 ctrl.getCurrentDisplayValue = getCurrentDisplayValue;
77 ctrl.registerSelectedItemWatcher = registerSelectedItemWatcher;
78 ctrl.unregisterSelectedItemWatcher = unregisterSelectedItemWatcher;
79 ctrl.notFoundVisible = notFoundVisible;
80 ctrl.loadingIsVisible = loadingIsVisible;
81 ctrl.positionDropdown = positionDropdown;
84 * Report types to be used for the $mdLiveAnnouncer
85 * @enum {number} Unique flag id.
94 //-- initialization methods
97 * Initialize the controller, setup watchers, gather elements
101 $mdUtil.initOptionalProperties($scope, $attrs, {
107 $mdTheming($element);
109 $mdUtil.nextTick(function () {
114 // Forward all focus events to the input element when autofocus is enabled
115 if ($scope.autofocus) {
116 $element.on('focus', focusInputElement);
121 function updateModelValidators() {
122 if (!$scope.requireMatch || !inputModelCtrl) return;
124 inputModelCtrl.$setValidity('md-require-match', !!$scope.selectedItem || !$scope.searchText);
128 * Calculates the dropdown's position and applies the new styles to the menu element
131 function positionDropdown () {
133 return $mdUtil.nextTick(positionDropdown, false, $scope);
136 var dropdownHeight = ($scope.dropdownItems || MAX_ITEMS) * ITEM_HEIGHT;
138 var hrect = elements.wrap.getBoundingClientRect(),
139 vrect = elements.snap.getBoundingClientRect(),
140 root = elements.root.getBoundingClientRect(),
141 top = vrect.bottom - root.top,
142 bot = root.bottom - vrect.top,
143 left = hrect.left - root.left,
145 offset = getVerticalOffset(),
146 position = $scope.dropdownPosition,
149 // Automatically determine dropdown placement based on available space in viewport.
151 position = (top > bot && root.height - hrect.bottom - MENU_PADDING < dropdownHeight) ? 'top' : 'bottom';
153 // Adjust the width to account for the padding provided by `md-input-container`
154 if ($attrs.mdFloatingLabel) {
155 left += INPUT_PADDING;
156 width -= INPUT_PADDING * 2;
160 minWidth: width + 'px',
161 maxWidth: Math.max(hrect.right - root.left, root.right - hrect.left) - MENU_PADDING + 'px'
164 if (position === 'top') {
166 styles.bottom = bot + 'px';
167 styles.maxHeight = Math.min(dropdownHeight, hrect.top - root.top - MENU_PADDING) + 'px';
169 var bottomSpace = root.bottom - hrect.bottom - MENU_PADDING + $mdUtil.getViewportTop();
171 styles.top = (top - offset) + 'px';
172 styles.bottom = 'auto';
173 styles.maxHeight = Math.min(dropdownHeight, bottomSpace) + 'px';
176 elements.$.scrollContainer.css(styles);
177 $mdUtil.nextTick(correctHorizontalAlignment, false);
180 * Calculates the vertical offset for floating label examples to account for ngMessages
183 function getVerticalOffset () {
185 var inputContainer = $element.find('md-input-container');
186 if (inputContainer.length) {
187 var input = inputContainer.find('input');
188 offset = inputContainer.prop('offsetHeight');
189 offset -= input.prop('offsetTop');
190 offset -= input.prop('offsetHeight');
191 // add in the height left up top for the floating label text
192 offset += inputContainer.prop('offsetTop');
198 * Makes sure that the menu doesn't go off of the screen on either side.
200 function correctHorizontalAlignment () {
201 var dropdown = elements.scrollContainer.getBoundingClientRect(),
203 if (dropdown.right > root.right - MENU_PADDING) {
204 styles.left = (hrect.right - dropdown.width) + 'px';
206 elements.$.scrollContainer.css(styles);
211 * Moves the dropdown menu to the body tag in order to avoid z-index and overflow issues.
213 function moveDropdown () {
214 if (!elements.$.root.length) return;
215 $mdTheming(elements.$.scrollContainer);
216 elements.$.scrollContainer.detach();
217 elements.$.root.append(elements.$.scrollContainer);
218 if ($animate.pin) $animate.pin(elements.$.scrollContainer, $rootElement);
222 * Sends focus to the input element.
224 function focusInputElement () {
225 elements.input.focus();
229 * Sets up any watchers used by autocomplete
231 function configureWatchers () {
232 var wait = parseInt($scope.delay, 10) || 0;
234 $attrs.$observe('disabled', function (value) { ctrl.isDisabled = $mdUtil.parseAttributeBoolean(value, false); });
235 $attrs.$observe('required', function (value) { ctrl.isRequired = $mdUtil.parseAttributeBoolean(value, false); });
236 $attrs.$observe('readonly', function (value) { ctrl.isReadonly = $mdUtil.parseAttributeBoolean(value, false); });
238 $scope.$watch('searchText', wait ? $mdUtil.debounce(handleSearchText, wait) : handleSearchText);
239 $scope.$watch('selectedItem', selectedItemChange);
241 angular.element($window).on('resize', debouncedOnResize);
243 $scope.$on('$destroy', cleanup);
247 * Removes any events or leftover elements created by this controller
249 function cleanup () {
251 $mdUtil.enableScrolling();
254 angular.element($window).off('resize', debouncedOnResize);
257 var items = ['ul', 'scroller', 'scrollContainer', 'input'];
258 angular.forEach(items, function(key){
259 elements.$[key].remove();
265 * Event handler to be called whenever the window resizes.
267 function onWindowResize() {
274 * Gathers all of the elements needed for this controller
276 function gatherElements () {
278 var snapWrap = gatherSnapWrap();
282 scrollContainer: $element[0].querySelector('.md-virtual-repeat-container'),
283 scroller: $element[0].querySelector('.md-virtual-repeat-scroller'),
284 ul: $element.find('ul')[0],
285 input: $element.find('input')[0],
291 elements.li = elements.ul.getElementsByTagName('li');
292 elements.$ = getAngularElements(elements);
294 inputModelCtrl = elements.$.input.controller('ngModel');
298 * Gathers the snap and wrap elements
301 function gatherSnapWrap() {
304 for (element = $element; element.length; element = element.parent()) {
305 value = element.attr('md-autocomplete-snap');
306 if (angular.isDefined(value)) break;
309 if (element.length) {
312 wrap: (value.toLowerCase() === 'width') ? element[0] : $element.find('md-autocomplete-wrap')[0]
316 var wrap = $element.find('md-autocomplete-wrap')[0];
324 * Gathers angular-wrapped versions of each element
328 function getAngularElements (elements) {
330 for (var key in elements) {
331 if (elements.hasOwnProperty(key)) obj[ key ] = angular.element(elements[ key ]);
336 //-- event/change handlers
339 * Handles changes to the `hidden` property.
343 function handleHiddenChange (hidden, oldHidden) {
344 if (!hidden && oldHidden) {
347 // Report in polite mode, because the screenreader should finish the default description of
348 // the input. element.
349 reportMessages(true, ReportType.Count | ReportType.Selected);
352 $mdUtil.disableScrollAround(elements.ul);
353 enableWrapScroll = disableElementScrollEvents(angular.element(elements.wrap));
355 } else if (hidden && !oldHidden) {
356 $mdUtil.enableScrolling();
358 if (enableWrapScroll) {
360 enableWrapScroll = null;
366 * Disables scrolling for a specific element
368 function disableElementScrollEvents(element) {
370 function preventDefault(e) {
374 element.on('wheel', preventDefault);
375 element.on('touchmove', preventDefault);
378 element.off('wheel', preventDefault);
379 element.off('touchmove', preventDefault);
384 * When the user mouses over the dropdown menu, ignore blur events.
386 function onListEnter () {
391 * When the user's mouse leaves the menu, blur events may hide the menu again.
393 function onListLeave () {
394 if (!hasFocus && !ctrl.hidden) elements.input.focus();
396 ctrl.hidden = shouldHide();
400 * When the mouse button is released, send focus back to the input field.
402 function onMouseup () {
403 elements.input.focus();
407 * Handles changes to the selected item.
408 * @param selectedItem
409 * @param previousSelectedItem
411 function selectedItemChange (selectedItem, previousSelectedItem) {
413 updateModelValidators();
416 getDisplayValue(selectedItem).then(function (val) {
417 $scope.searchText = val;
418 handleSelectedItemChange(selectedItem, previousSelectedItem);
420 } else if (previousSelectedItem && $scope.searchText) {
421 getDisplayValue(previousSelectedItem).then(function(displayValue) {
422 // Clear the searchText, when the selectedItem is set to null.
423 // Do not clear the searchText, when the searchText isn't matching with the previous
425 if (angular.isString($scope.searchText)
426 && displayValue.toString().toLowerCase() === $scope.searchText.toLowerCase()) {
427 $scope.searchText = '';
432 if (selectedItem !== previousSelectedItem) announceItemChange();
436 * Use the user-defined expression to announce changes each time a new item is selected
438 function announceItemChange () {
439 angular.isFunction($scope.itemChange) && $scope.itemChange(getItemAsNameVal($scope.selectedItem));
443 * Use the user-defined expression to announce changes each time the search text is changed
445 function announceTextChange () {
446 angular.isFunction($scope.textChange) && $scope.textChange();
450 * Calls any external watchers listening for the selected item. Used in conjunction with
451 * `registerSelectedItemWatcher`.
452 * @param selectedItem
453 * @param previousSelectedItem
455 function handleSelectedItemChange (selectedItem, previousSelectedItem) {
456 selectedItemWatchers.forEach(function (watcher) { watcher(selectedItem, previousSelectedItem); });
460 * Register a function to be called when the selected item changes.
463 function registerSelectedItemWatcher (cb) {
464 if (selectedItemWatchers.indexOf(cb) == -1) {
465 selectedItemWatchers.push(cb);
470 * Unregister a function previously registered for selected item changes.
473 function unregisterSelectedItemWatcher (cb) {
474 var i = selectedItemWatchers.indexOf(cb);
476 selectedItemWatchers.splice(i, 1);
481 * Handles changes to the searchText property.
483 * @param previousSearchText
485 function handleSearchText (searchText, previousSearchText) {
486 ctrl.index = getDefaultIndex();
488 // do nothing on init
489 if (searchText === previousSearchText) return;
491 updateModelValidators();
493 getDisplayValue($scope.selectedItem).then(function (val) {
494 // clear selected item if search text no longer matches it
495 if (searchText !== val) {
496 $scope.selectedItem = null;
499 // trigger change event if available
500 if (searchText !== previousSearchText) announceTextChange();
502 // cancel results if search text is not long enough
503 if (!isMinLengthMet()) {
507 reportMessages(false, ReportType.Count);
518 * Handles input blur event, determines if the dropdown should hide.
520 function blur($event) {
524 ctrl.hidden = shouldHide();
525 evalAttr('ngBlur', { $event: $event });
530 * Force blur on input element
533 function doBlur(forceBlur) {
538 elements.input.blur();
542 * Handles input focus event, determines if the dropdown should show.
544 function focus($event) {
547 if (isSearchable() && isMinLengthMet()) {
551 ctrl.hidden = shouldHide();
553 evalAttr('ngFocus', { $event: $event });
557 * Handles keyboard input.
560 function keydown (event) {
561 switch (event.keyCode) {
562 case $mdConstant.KEY_CODE.DOWN_ARROW:
563 if (ctrl.loading) return;
564 event.stopPropagation();
565 event.preventDefault();
566 ctrl.index = Math.min(ctrl.index + 1, ctrl.matches.length - 1);
568 reportMessages(false, ReportType.Selected);
570 case $mdConstant.KEY_CODE.UP_ARROW:
571 if (ctrl.loading) return;
572 event.stopPropagation();
573 event.preventDefault();
574 ctrl.index = ctrl.index < 0 ? ctrl.matches.length - 1 : Math.max(0, ctrl.index - 1);
576 reportMessages(false, ReportType.Selected);
578 case $mdConstant.KEY_CODE.TAB:
579 // If we hit tab, assume that we've left the list so it will close
582 if (ctrl.hidden || ctrl.loading || ctrl.index < 0 || ctrl.matches.length < 1) return;
585 case $mdConstant.KEY_CODE.ENTER:
586 if (ctrl.hidden || ctrl.loading || ctrl.index < 0 || ctrl.matches.length < 1) return;
587 if (hasSelection()) return;
588 event.stopPropagation();
589 event.preventDefault();
592 case $mdConstant.KEY_CODE.ESCAPE:
593 event.preventDefault(); // Prevent browser from always clearing input
594 if (!shouldProcessEscape()) return;
595 event.stopPropagation();
598 if ($scope.searchText && hasEscapeOption('clear')) {
602 // Manually hide (needed for mdNotFound support)
605 if (hasEscapeOption('blur')) {
606 // Force the component to blur if they hit escape
618 * Returns the minimum length needed to display the dropdown.
621 function getMinLength () {
622 return angular.isNumber($scope.minLength) ? $scope.minLength : 1;
626 * Returns the display value for an item.
630 function getDisplayValue (item) {
631 return $q.when(getItemText(item) || item).then(function(itemText) {
632 if (itemText && !angular.isString(itemText)) {
633 $log.warn('md-autocomplete: Could not resolve display value to a string. ' +
634 'Please check the `md-item-text` attribute.');
641 * Getter function to invoke user-defined expression (in the directive)
642 * to convert your object to a single string.
644 function getItemText (item) {
645 return (item && $scope.itemText) ? $scope.itemText(getItemAsNameVal(item)) : null;
650 * Returns the locals object for compiling item templates.
654 function getItemAsNameVal (item) {
655 if (!item) return undefined;
658 if (ctrl.itemName) locals[ ctrl.itemName ] = item;
664 * Returns the default index based on whether or not autoselect is enabled.
667 function getDefaultIndex () {
668 return $scope.autoselect ? 0 : -1;
672 * Sets the loading parameter and updates the hidden state.
673 * @param value {boolean} Whether or not the component is currently loading.
675 function setLoading(value) {
676 if (ctrl.loading != value) {
677 ctrl.loading = value;
680 // Always refresh the hidden variable as something else might have changed
681 ctrl.hidden = shouldHide();
685 * Determines if the menu should be hidden.
688 function shouldHide () {
689 if (!isSearchable()) return true; // Hide when not able to query
690 else return !shouldShow(); // Hide when the dropdown is not able to show.
694 * Determines whether the autocomplete is able to query within the current state.
697 function isSearchable() {
698 if (ctrl.loading && !hasMatches()) return false; // No query when query is in progress.
699 else if (hasSelection()) return false; // No query if there is already a selection
700 else if (!hasFocus) return false; // No query if the input does not have focus
705 * Determines if the escape keydown should be processed
708 function shouldProcessEscape() {
709 return hasEscapeOption('blur') || !ctrl.hidden || ctrl.loading || hasEscapeOption('clear') && $scope.searchText;
713 * Determines if an escape option is set
716 function hasEscapeOption(option) {
717 return !$scope.escapeOptions || $scope.escapeOptions.toLowerCase().indexOf(option) !== -1;
721 * Determines if the menu should be shown.
724 function shouldShow() {
725 return (isMinLengthMet() && hasMatches()) || notFoundVisible();
729 * Returns true if the search text has matches.
732 function hasMatches() {
733 return ctrl.matches.length ? true : false;
737 * Returns true if the autocomplete has a valid selection.
740 function hasSelection() {
741 return ctrl.scope.selectedItem ? true : false;
745 * Returns true if the loading indicator is, or should be, visible.
748 function loadingIsVisible() {
749 return ctrl.loading && !hasSelection();
753 * Returns the display value of the current item.
756 function getCurrentDisplayValue () {
757 return getDisplayValue(ctrl.matches[ ctrl.index ]);
761 * Determines if the minimum length is met by the search text.
764 function isMinLengthMet () {
765 return ($scope.searchText || '').length >= getMinLength();
771 * Defines a public property with a handler and a default value.
776 function defineProperty (key, handler, value) {
777 Object.defineProperty(ctrl, key, {
778 get: function () { return value; },
779 set: function (newValue) {
780 var oldValue = value;
782 handler(newValue, oldValue);
788 * Selects the item at the given index.
791 function select (index) {
792 //-- force form to update state for validation
793 $mdUtil.nextTick(function () {
794 getDisplayValue(ctrl.matches[ index ]).then(function (val) {
795 var ngModel = elements.$.input.controller('ngModel');
796 ngModel.$setViewValue(val);
798 }).finally(function () {
799 $scope.selectedItem = ctrl.matches[ index ];
806 * Clears the searchText value and selected item.
808 function clearValue () {
814 * Clears the selected item
816 function clearSelectedItem () {
817 // Reset our variables
823 * Clears the searchText value
825 function clearSearchText () {
826 // Set the loading to true so we don't see flashes of content.
827 // The flashing will only occur when an async request is running.
828 // So the loading process will stop when the results had been retrieved.
831 $scope.searchText = '';
833 // Normally, triggering the change / input event is unnecessary, because the browser detects it properly.
834 // But some browsers are not detecting it properly, which means that we have to trigger the event.
835 // Using the `input` is not working properly, because for example IE11 is not supporting the `input` event.
836 // The `change` event is a good alternative and is supported by all supported browsers.
837 var eventObj = document.createEvent('CustomEvent');
838 eventObj.initCustomEvent('change', true, true, { value: '' });
839 elements.input.dispatchEvent(eventObj);
841 // For some reason, firing the above event resets the value of $scope.searchText if
842 // $scope.searchText has a space character at the end, so we blank it one more time and then
844 elements.input.blur();
845 $scope.searchText = '';
846 elements.input.focus();
850 * Fetches the results for the provided search text.
853 function fetchResults (searchText) {
854 var items = $scope.$parent.$eval(itemExpr),
855 term = searchText.toLowerCase(),
856 isList = angular.isArray(items),
857 isPromise = !!items.then; // Every promise should contain a `then` property
859 if (isList) onResultsRetrieved(items);
860 else if (isPromise) handleAsyncResults(items);
862 function handleAsyncResults(items) {
863 if ( !items ) return;
865 items = $q.when(items);
869 $mdUtil.nextTick(function () {
871 .then(onResultsRetrieved)
873 if (--fetchesInProgress === 0) {
880 function onResultsRetrieved(matches) {
881 cache[term] = matches;
883 // Just cache the results if the request is now outdated.
884 // The request becomes outdated, when the new searchText has changed during the result fetching.
885 if ((searchText || '') !== ($scope.searchText || '')) {
889 handleResults(matches);
895 * Reports given message types to supported screenreaders.
896 * @param {boolean} isPolite Whether the announcement should be polite.
897 * @param {!number} types Message flags to be reported to the screenreader.
899 function reportMessages(isPolite, types) {
901 var politeness = isPolite ? 'polite' : 'assertive';
904 if (types & ReportType.Selected && ctrl.index !== -1) {
905 messages.push(getCurrentDisplayValue());
908 if (types & ReportType.Count) {
909 messages.push($q.resolve(getCountMessage()));
912 $q.all(messages).then(function(data) {
913 $mdLiveAnnouncer.announce(data.join(' '), politeness);
919 * Returns the ARIA message for how many results match the current query.
922 function getCountMessage () {
923 switch (ctrl.matches.length) {
925 return 'There are no matches available.';
927 return 'There is 1 match available.';
929 return 'There are ' + ctrl.matches.length + ' matches available.';
934 * Makes sure that the focused element is within view.
936 function updateScroll () {
937 if (!elements.li[0]) return;
938 var height = elements.li[0].offsetHeight,
939 top = height * ctrl.index,
941 hgt = elements.scroller.clientHeight,
942 scrollTop = elements.scroller.scrollTop;
943 if (top < scrollTop) {
945 } else if (bot > scrollTop + hgt) {
950 function isPromiseFetching() {
951 return fetchesInProgress !== 0;
954 function scrollTo (offset) {
955 elements.$.scrollContainer.controller('mdVirtualRepeatContainer').scrollTo(offset);
958 function notFoundVisible () {
959 var textLength = (ctrl.scope.searchText || '').length;
961 return ctrl.hasNotFound && !hasMatches() && (!ctrl.loading || isPromiseFetching()) && textLength >= getMinLength() && (hasFocus || noBlur) && !hasSelection();
965 * Starts the query to gather the results for the current searchText. Attempts to return cached
966 * results first, then forwards the process to `fetchResults` if necessary.
968 function handleQuery () {
969 var searchText = $scope.searchText || '';
970 var term = searchText.toLowerCase();
972 // If caching is enabled and the current searchText is stored in the cache
973 if (!$scope.noCache && cache[term]) {
974 // The results should be handled as same as a normal un-cached request does.
975 handleResults(cache[term]);
977 fetchResults(searchText);
980 ctrl.hidden = shouldHide();
984 * Handles the retrieved results by showing them in the autocompletes dropdown.
985 * @param results Retrieved results
987 function handleResults(results) {
988 ctrl.matches = results;
989 ctrl.hidden = shouldHide();
991 // If loading is in progress, then we'll end the progress. This is needed for example,
992 // when the `clear` button was clicked, because there we always show the loading process, to prevent flashing.
993 if (ctrl.loading) setLoading(false);
995 if ($scope.selectOnMatch) selectItemOnMatch();
998 reportMessages(true, ReportType.Count);
1002 * If there is only one matching item and the search text matches its display value exactly,
1003 * automatically select that item. Note: This function is only called if the user uses the
1004 * `md-select-on-match` flag.
1006 function selectItemOnMatch () {
1007 var searchText = $scope.searchText,
1008 matches = ctrl.matches,
1009 item = matches[ 0 ];
1010 if (matches.length === 1) getDisplayValue(item).then(function (displayValue) {
1011 var isMatching = searchText == displayValue;
1012 if ($scope.matchInsensitive && !isMatching) {
1013 isMatching = searchText.toLowerCase() == displayValue.toLowerCase();
1016 if (isMatching) select(0);
1021 * Evaluates an attribute expression against the parent scope.
1022 * @param {String} attr Name of the attribute to be evaluated.
1023 * @param {Object?} locals Properties to be injected into the evaluation context.
1025 function evalAttr(attr, locals) {
1027 $scope.$parent.$eval($attrs[attr], locals || {});
1034 MdAutocomplete['$inject'] = ["$$mdSvgRegistry"];angular
1035 .module('material.components.autocomplete')
1036 .directive('mdAutocomplete', MdAutocomplete);
1040 * @name mdAutocomplete
1041 * @module material.components.autocomplete
1044 * `<md-autocomplete>` is a special input component with a drop-down of all possible matches to a
1045 * custom query. This component allows you to provide real-time suggestions as the user types
1046 * in the input area.
1048 * To start, you will need to specify the required parameters and provide a template for your
1049 * results. The content inside `md-autocomplete` will be treated as a template.
1051 * In more complex cases, you may want to include other content such as a message to display when
1052 * no matches were found. You can do this by wrapping your template in `md-item-template` and
1053 * adding a tag for `md-not-found`. An example of this is shown below.
1055 * To reset the displayed value you must clear both values for `md-search-text` and `md-selected-item`.
1059 * You can use `ng-messages` to include validation the same way that you would normally validate;
1060 * however, if you want to replicate a standard input with a floating label, you will have to
1063 * - Make sure that your template is wrapped in `md-item-template`
1064 * - Add your `ng-messages` code inside of `md-autocomplete`
1065 * - Add your validation properties to `md-autocomplete` (ie. `required`)
1066 * - Add a `name` to `md-autocomplete` (to be used on the generated `input`)
1068 * There is an example below of how this should look.
1070 * ### Snapping Drop-Down
1072 * You can cause the autocomplete drop-down to snap to an ancestor element by applying the
1073 * `md-autocomplete-snap` attribute to that element. You can also snap to the width of
1074 * the `md-autocomplete-snap` element by setting the attribute's value to `width`
1075 * (ie. `md-autocomplete-snap="width"`).
1079 * **Autocomplete Dropdown Items Rendering**
1081 * The `md-autocomplete` uses the the <a ng-href="api/directive/mdVirtualRepeatContainer">VirtualRepeat</a>
1082 * directive for displaying the results inside of the dropdown.<br/>
1084 * > When encountering issues regarding the item template please take a look at the
1085 * <a ng-href="api/directive/mdVirtualRepeatContainer">VirtualRepeatContainer</a> documentation.
1087 * **Autocomplete inside of a Virtual Repeat**
1089 * When using the `md-autocomplete` directive inside of a
1090 * <a ng-href="api/directive/mdVirtualRepeatContainer">VirtualRepeatContainer</a> the dropdown items might
1091 * not update properly, because caching of the results is enabled by default.
1093 * The autocomplete will then show invalid dropdown items, because the VirtualRepeat only updates the
1094 * scope bindings, rather than re-creating the `md-autocomplete` and the previous cached results will be used.
1096 * > To avoid such problems ensure that the autocomplete does not cache any results.
1098 * <hljs lang="html">
1100 * md-no-cache="true"
1101 * md-selected-item="selectedItem"
1102 * md-items="item in items"
1103 * md-search-text="searchText"
1104 * md-item-text="item.display">
1105 * <span>{{ item.display }}</span>
1106 * </md-autocomplete>
1111 * @param {expression} md-items An expression in the format of `item in results` to iterate over
1112 * matches for your search.<br/><br/>
1113 * The `results` expression can be also a function, which returns the results synchronously
1114 * or asynchronously (per Promise)
1115 * @param {expression=} md-selected-item-change An expression to be run each time a new item is
1117 * @param {expression=} md-search-text-change An expression to be run each time the search text
1119 * @param {expression=} md-search-text A model to bind the search query text to
1120 * @param {object=} md-selected-item A model to bind the selected item to
1121 * @param {expression=} md-item-text An expression that will convert your object to a single string.
1122 * @param {string=} placeholder Placeholder text that will be forwarded to the input.
1123 * @param {boolean=} md-no-cache Disables the internal caching that happens in autocomplete
1124 * @param {boolean=} ng-disabled Determines whether or not to disable the input field
1125 * @param {boolean=} md-require-match When set to true, the autocomplete will add a validator,
1126 * which will evaluate to false, when no item is currently selected.
1127 * @param {number=} md-min-length Specifies the minimum length of text before autocomplete will
1129 * @param {number=} md-delay Specifies the amount of time (in milliseconds) to wait before looking
1131 * @param {boolean=} md-clear-button Whether the clear button for the autocomplete input should show up or not.
1132 * @param {boolean=} md-autofocus If true, the autocomplete will be automatically focused when a `$mdDialog`,
1133 * `$mdBottomsheet` or `$mdSidenav`, which contains the autocomplete, is opening. <br/><br/>
1134 * Also the autocomplete will immediately focus the input element.
1135 * @param {boolean=} md-no-asterisk When present, asterisk will not be appended to the floating label
1136 * @param {boolean=} md-autoselect If set to true, the first item will be automatically selected
1137 * in the dropdown upon open.
1138 * @param {string=} md-menu-class This will be applied to the dropdown menu for styling
1139 * @param {string=} md-floating-label This will add a floating label to autocomplete and wrap it in
1140 * `md-input-container`
1141 * @param {string=} md-input-name The name attribute given to the input element to be used with
1143 * @param {string=} md-select-on-focus When present the inputs text will be automatically selected
1145 * @param {string=} md-input-id An ID to be added to the input element
1146 * @param {number=} md-input-minlength The minimum length for the input's value for validation
1147 * @param {number=} md-input-maxlength The maximum length for the input's value for validation
1148 * @param {boolean=} md-select-on-match When set, autocomplete will automatically select exact
1149 * the item if the search text is an exact match. <br/><br/>
1150 * Exact match means that there is only one match showing up.
1151 * @param {boolean=} md-match-case-insensitive When set and using `md-select-on-match`, autocomplete
1152 * will select on case-insensitive match
1153 * @param {string=} md-escape-options Override escape key logic. Default is `blur clear`.<br/>
1154 * Options: `blur | clear`, `none`
1155 * @param {string=} md-dropdown-items Specifies the maximum amount of items to be shown in
1156 * the dropdown.<br/><br/>
1157 * When the dropdown doesn't fit into the viewport, the dropdown will shrink
1158 * as less as possible.
1159 * @param {string=} md-dropdown-position Overrides the default dropdown position. Options: `top`, `bottom`.
1160 * @param {string=} ng-trim If set to false, the search text will be not trimmed automatically.
1162 * @param {string=} ng-pattern Adds the pattern validator to the ngModel of the search text.
1163 * [ngPattern Directive](https://docs.angularjs.org/api/ng/directive/ngPattern)
1167 * <hljs lang="html">
1169 * md-selected-item="selectedItem"
1170 * md-search-text="searchText"
1171 * md-items="item in getMatches(searchText)"
1172 * md-item-text="item.display">
1173 * <span md-highlight-text="searchText">{{item.display}}</span>
1174 * </md-autocomplete>
1177 * ### Example with "not found" message
1178 * <hljs lang="html">
1180 * md-selected-item="selectedItem"
1181 * md-search-text="searchText"
1182 * md-items="item in getMatches(searchText)"
1183 * md-item-text="item.display">
1184 * <md-item-template>
1185 * <span md-highlight-text="searchText">{{item.display}}</span>
1186 * </md-item-template>
1190 * </md-autocomplete>
1193 * In this example, our code utilizes `md-item-template` and `md-not-found` to specify the
1194 * different parts that make up our component.
1196 * ### Clear button for the input
1197 * By default, for floating label autocomplete's the clear button is not showing up
1198 * ([See specs](https://material.google.com/components/text-fields.html#text-fields-auto-complete-text-field))
1200 * Nevertheless, developers are able to explicitly toggle the clear button for all types of autocomplete's.
1202 * <hljs lang="html">
1203 * <md-autocomplete ... md-clear-button="true"></md-autocomplete>
1204 * <md-autocomplete ... md-clear-button="false"></md-autocomplete>
1207 * ### Example with validation
1208 * <hljs lang="html">
1209 * <form name="autocompleteForm">
1212 * md-input-name="autocomplete"
1213 * md-selected-item="selectedItem"
1214 * md-search-text="searchText"
1215 * md-items="item in getMatches(searchText)"
1216 * md-item-text="item.display">
1217 * <md-item-template>
1218 * <span md-highlight-text="searchText">{{item.display}}</span>
1219 * </md-item-template>
1220 * <div ng-messages="autocompleteForm.autocomplete.$error">
1221 * <div ng-message="required">This field is required</div>
1223 * </md-autocomplete>
1227 * In this example, our code utilizes `md-item-template` and `ng-messages` to specify
1228 * input validation for the field.
1230 * ### Asynchronous Results
1231 * The autocomplete items expression also supports promises, which will resolve with the query results.
1234 * function AppController($scope, $http) {
1235 * $scope.query = function(searchText) {
1237 * .get(BACKEND_URL + '/items/' + searchText)
1238 * .then(function(data) {
1239 * // Map the response object to the data object.
1246 * <hljs lang="html">
1248 * md-selected-item="selectedItem"
1249 * md-search-text="searchText"
1250 * md-items="item in query(searchText)">
1251 * <md-item-template>
1252 * <span md-highlight-text="searchText">{{item}}</span>
1253 * </md-item-template>
1254 * </md-autocomplete>
1259 function MdAutocomplete ($$mdSvgRegistry) {
1262 controller: 'MdAutocompleteCtrl',
1263 controllerAs: '$mdAutocompleteCtrl',
1265 inputName: '@mdInputName',
1266 inputMinlength: '@mdInputMinlength',
1267 inputMaxlength: '@mdInputMaxlength',
1268 searchText: '=?mdSearchText',
1269 selectedItem: '=?mdSelectedItem',
1270 itemsExpr: '@mdItems',
1271 itemText: '&mdItemText',
1272 placeholder: '@placeholder',
1273 noCache: '=?mdNoCache',
1274 requireMatch: '=?mdRequireMatch',
1275 selectOnMatch: '=?mdSelectOnMatch',
1276 matchInsensitive: '=?mdMatchCaseInsensitive',
1277 itemChange: '&?mdSelectedItemChange',
1278 textChange: '&?mdSearchTextChange',
1279 minLength: '=?mdMinLength',
1281 autofocus: '=?mdAutofocus',
1282 floatingLabel: '@?mdFloatingLabel',
1283 autoselect: '=?mdAutoselect',
1284 menuClass: '@?mdMenuClass',
1285 inputId: '@?mdInputId',
1286 escapeOptions: '@?mdEscapeOptions',
1287 dropdownItems: '=?mdDropdownItems',
1288 dropdownPosition: '@?mdDropdownPosition',
1289 clearButton: '=?mdClearButton'
1291 compile: function(tElement, tAttrs) {
1292 var attributes = ['md-select-on-focus', 'md-no-asterisk', 'ng-trim', 'ng-pattern'];
1293 var input = tElement.find('input');
1295 attributes.forEach(function(attribute) {
1296 var attrValue = tAttrs[tAttrs.$normalize(attribute)];
1298 if (attrValue !== null) {
1299 input.attr(attribute, attrValue);
1303 return function(scope, element, attrs, ctrl) {
1304 // Retrieve the state of using a md-not-found template by using our attribute, which will
1305 // be added to the element in the template function.
1306 ctrl.hasNotFound = !!element.attr('md-has-not-found');
1308 // By default the inset autocomplete should show the clear button when not explicitly overwritten.
1309 if (!angular.isDefined(attrs.mdClearButton) && !scope.floatingLabel) {
1310 scope.clearButton = true;
1314 template: function (element, attr) {
1315 var noItemsTemplate = getNoItemsTemplate(),
1316 itemTemplate = getItemTemplate(),
1317 leftover = element.html(),
1318 tabindex = attr.tabindex;
1320 // Set our attribute for the link function above which runs later.
1321 // We will set an attribute, because otherwise the stored variables will be trashed when
1322 // removing the element is hidden while retrieving the template. For example when using ngIf.
1323 if (noItemsTemplate) element.attr('md-has-not-found', true);
1325 // Always set our tabindex of the autocomplete directive to -1, because our input
1326 // will hold the actual tabindex.
1327 element.attr('tabindex', '-1');
1330 <md-autocomplete-wrap\
1331 ng-class="{ \'md-whiteframe-z1\': !floatingLabel, \
1332 \'md-menu-showing\': !$mdAutocompleteCtrl.hidden, \
1333 \'md-show-clear-button\': !!clearButton }">\
1334 ' + getInputElement() + '\
1335 ' + getClearButton() + '\
1336 <md-progress-linear\
1337 class="' + (attr.mdFloatingLabel ? 'md-inline' : '') + '"\
1338 ng-if="$mdAutocompleteCtrl.loadingIsVisible()"\
1339 md-mode="indeterminate"></md-progress-linear>\
1340 <md-virtual-repeat-container\
1342 md-auto-shrink-min="1"\
1343 ng-mouseenter="$mdAutocompleteCtrl.listEnter()"\
1344 ng-mouseleave="$mdAutocompleteCtrl.listLeave()"\
1345 ng-mouseup="$mdAutocompleteCtrl.mouseUp()"\
1346 ng-hide="$mdAutocompleteCtrl.hidden"\
1347 class="md-autocomplete-suggestions-container md-whiteframe-z1"\
1348 ng-class="{ \'md-not-found\': $mdAutocompleteCtrl.notFoundVisible() }"\
1349 role="presentation">\
1350 <ul class="md-autocomplete-suggestions"\
1351 ng-class="::menuClass"\
1352 id="ul-{{$mdAutocompleteCtrl.id}}">\
1353 <li md-virtual-repeat="item in $mdAutocompleteCtrl.matches"\
1354 ng-class="{ selected: $index === $mdAutocompleteCtrl.index }"\
1355 ng-click="$mdAutocompleteCtrl.select($index)"\
1356 md-extra-name="$mdAutocompleteCtrl.itemName">\
1357 ' + itemTemplate + '\
1358 </li>' + noItemsTemplate + '\
1360 </md-virtual-repeat-container>\
1361 </md-autocomplete-wrap>';
1363 function getItemTemplate() {
1364 var templateTag = element.find('md-item-template').detach(),
1365 html = templateTag.length ? templateTag.html() : element.html();
1366 if (!templateTag.length) element.empty();
1367 return '<md-autocomplete-parent-scope md-autocomplete-replace>' + html + '</md-autocomplete-parent-scope>';
1370 function getNoItemsTemplate() {
1371 var templateTag = element.find('md-not-found').detach(),
1372 template = templateTag.length ? templateTag.html() : '';
1374 ? '<li ng-if="$mdAutocompleteCtrl.notFoundVisible()"\
1375 md-autocomplete-parent-scope>' + template + '</li>'
1380 function getInputElement () {
1381 if (attr.mdFloatingLabel) {
1383 <md-input-container ng-if="floatingLabel">\
1384 <label>{{floatingLabel}}</label>\
1385 <input type="search"\
1386 ' + (tabindex != null ? 'tabindex="' + tabindex + '"' : '') + '\
1387 id="{{ inputId || \'fl-input-\' + $mdAutocompleteCtrl.id }}"\
1388 name="{{inputName}}"\
1390 ng-required="$mdAutocompleteCtrl.isRequired"\
1391 ng-readonly="$mdAutocompleteCtrl.isReadonly"\
1392 ng-minlength="inputMinlength"\
1393 ng-maxlength="inputMaxlength"\
1394 ng-disabled="$mdAutocompleteCtrl.isDisabled"\
1395 ng-model="$mdAutocompleteCtrl.scope.searchText"\
1396 ng-model-options="{ allowInvalid: true }"\
1397 ng-keydown="$mdAutocompleteCtrl.keydown($event)"\
1398 ng-blur="$mdAutocompleteCtrl.blur($event)"\
1399 ng-focus="$mdAutocompleteCtrl.focus($event)"\
1400 aria-owns="ul-{{$mdAutocompleteCtrl.id}}"\
1401 aria-label="{{floatingLabel}}"\
1402 aria-autocomplete="list"\
1404 aria-haspopup="true"\
1405 aria-activedescendant=""\
1406 aria-expanded="{{!$mdAutocompleteCtrl.hidden}}"/>\
1407 <div md-autocomplete-parent-scope md-autocomplete-replace>' + leftover + '</div>\
1408 </md-input-container>';
1411 <input type="search"\
1412 ' + (tabindex != null ? 'tabindex="' + tabindex + '"' : '') + '\
1413 id="{{ inputId || \'input-\' + $mdAutocompleteCtrl.id }}"\
1414 name="{{inputName}}"\
1415 ng-if="!floatingLabel"\
1417 ng-required="$mdAutocompleteCtrl.isRequired"\
1418 ng-disabled="$mdAutocompleteCtrl.isDisabled"\
1419 ng-readonly="$mdAutocompleteCtrl.isReadonly"\
1420 ng-minlength="inputMinlength"\
1421 ng-maxlength="inputMaxlength"\
1422 ng-model="$mdAutocompleteCtrl.scope.searchText"\
1423 ng-keydown="$mdAutocompleteCtrl.keydown($event)"\
1424 ng-blur="$mdAutocompleteCtrl.blur($event)"\
1425 ng-focus="$mdAutocompleteCtrl.focus($event)"\
1426 placeholder="{{placeholder}}"\
1427 aria-owns="ul-{{$mdAutocompleteCtrl.id}}"\
1428 aria-label="{{placeholder}}"\
1429 aria-autocomplete="list"\
1431 aria-haspopup="true"\
1432 aria-activedescendant=""\
1433 aria-expanded="{{!$mdAutocompleteCtrl.hidden}}"/>';
1437 function getClearButton() {
1441 'aria-label="Clear Input" ' +
1443 'ng-if="clearButton && $mdAutocompleteCtrl.scope.searchText && !$mdAutocompleteCtrl.isDisabled" ' +
1444 'ng-click="$mdAutocompleteCtrl.clear($event)">' +
1445 '<md-icon md-svg-src="' + $$mdSvgRegistry.mdClose + '"></md-icon>' +
1453 MdAutocompleteItemScopeDirective['$inject'] = ["$compile", "$mdUtil"];angular
1454 .module('material.components.autocomplete')
1455 .directive('mdAutocompleteParentScope', MdAutocompleteItemScopeDirective);
1457 function MdAutocompleteItemScopeDirective($compile, $mdUtil) {
1462 transclude: 'element'
1465 function compile(tElement, tAttr, transclude) {
1466 return function postLink(scope, element, attr) {
1467 var ctrl = scope.$mdAutocompleteCtrl;
1468 var newScope = ctrl.parent.$new();
1469 var itemName = ctrl.itemName;
1471 // Watch for changes to our scope's variables and copy them to the new scope
1472 watchVariable('$index', '$index');
1473 watchVariable('item', itemName);
1475 // Ensure that $digest calls on our scope trigger $digest on newScope.
1478 // Link the element against newScope.
1479 transclude(newScope, function(clone) {
1480 element.after(clone);
1484 * Creates a watcher for variables that are copied from the parent scope
1488 function watchVariable(variable, alias) {
1489 newScope[alias] = scope[variable];
1491 scope.$watch(variable, function(value) {
1492 $mdUtil.nextTick(function() {
1493 newScope[alias] = value;
1499 * Creates watchers on scope and newScope that ensure that for any
1500 * $digest of scope, newScope is also $digested.
1502 function connectScopes() {
1503 var scopeDigesting = false;
1504 var newScopeDigesting = false;
1506 scope.$watch(function() {
1507 if (newScopeDigesting || scopeDigesting) {
1511 scopeDigesting = true;
1512 scope.$$postDigest(function() {
1513 if (!newScopeDigesting) {
1517 scopeDigesting = newScopeDigesting = false;
1521 newScope.$watch(function() {
1522 newScopeDigesting = true;
1529 MdHighlightCtrl['$inject'] = ["$scope", "$element", "$attrs"];angular
1530 .module('material.components.autocomplete')
1531 .controller('MdHighlightCtrl', MdHighlightCtrl);
1533 function MdHighlightCtrl ($scope, $element, $attrs) {
1534 this.$scope = $scope;
1535 this.$element = $element;
1536 this.$attrs = $attrs;
1538 // Cache the Regex to avoid rebuilding each time.
1542 MdHighlightCtrl.prototype.init = function(unsafeTermFn, unsafeContentFn) {
1544 this.flags = this.$attrs.mdHighlightFlags || '';
1546 this.unregisterFn = this.$scope.$watch(function($scope) {
1548 term: unsafeTermFn($scope),
1549 contentText: unsafeContentFn($scope)
1551 }.bind(this), this.onRender.bind(this), true);
1553 this.$element.on('$destroy', this.unregisterFn);
1557 * Triggered once a new change has been recognized and the highlighted
1558 * text needs to be updated.
1560 MdHighlightCtrl.prototype.onRender = function(state, prevState) {
1562 var contentText = state.contentText;
1564 /* Update the regex if it's outdated, because we don't want to rebuilt it constantly. */
1565 if (this.regex === null || state.term !== prevState.term) {
1566 this.regex = this.createRegex(state.term, this.flags);
1569 /* If a term is available apply the regex to the content */
1571 this.applyRegex(contentText);
1573 this.$element.text(contentText);
1579 * Decomposes the specified text into different tokens (whether match or not).
1580 * Breaking down the string guarantees proper XSS protection due to the native browser
1581 * escaping of unsafe text.
1583 MdHighlightCtrl.prototype.applyRegex = function(text) {
1584 var tokens = this.resolveTokens(text);
1586 this.$element.empty();
1588 tokens.forEach(function (token) {
1590 if (token.isMatch) {
1591 var tokenEl = angular.element('<span class="highlight">').text(token.text);
1593 this.$element.append(tokenEl);
1595 this.$element.append(document.createTextNode(token));
1603 * Decomposes the specified text into different tokens by running the regex against the text.
1605 MdHighlightCtrl.prototype.resolveTokens = function(string) {
1609 // Use replace here, because it supports global and single regular expressions at same time.
1610 string.replace(this.regex, function(match, index) {
1611 appendToken(lastIndex, index);
1618 lastIndex = index + match.length;
1621 // Append the missing text as a token.
1622 appendToken(lastIndex);
1626 function appendToken(from, to) {
1627 var targetText = string.slice(from, to);
1628 targetText && tokens.push(targetText);
1632 /** Creates a regex for the specified text with the given flags. */
1633 MdHighlightCtrl.prototype.createRegex = function(term, flags) {
1634 var startFlag = '', endFlag = '';
1635 var regexTerm = this.sanitizeRegex(term);
1637 if (flags.indexOf('^') >= 0) startFlag = '^';
1638 if (flags.indexOf('$') >= 0) endFlag = '$';
1640 return new RegExp(startFlag + regexTerm + endFlag, flags.replace(/[$\^]/g, ''));
1643 /** Sanitizes a regex by removing all common RegExp identifiers */
1644 MdHighlightCtrl.prototype.sanitizeRegex = function(term) {
1645 return term && term.toString().replace(/[\\\^\$\*\+\?\.\(\)\|\{}\[\]]/g, '\\$&');
1649 MdHighlight['$inject'] = ["$interpolate", "$parse"];angular
1650 .module('material.components.autocomplete')
1651 .directive('mdHighlightText', MdHighlight);
1655 * @name mdHighlightText
1656 * @module material.components.autocomplete
1659 * The `md-highlight-text` directive allows you to specify text that should be highlighted within
1660 * an element. Highlighted text will be wrapped in `<span class="highlight"></span>` which can
1661 * be styled through CSS. Please note that child elements may not be used with this directive.
1663 * @param {string} md-highlight-text A model to be searched for
1664 * @param {string=} md-highlight-flags A list of flags (loosely based on JavaScript RexExp flags).
1665 * #### **Supported flags**:
1666 * - `g`: Find all matches within the provided text
1667 * - `i`: Ignore case when searching for matches
1668 * - `$`: Only match if the text ends with the search term
1669 * - `^`: Only match if the text begins with the search term
1672 * <hljs lang="html">
1673 * <input placeholder="Enter a search term..." ng-model="searchTerm" type="text" />
1675 * <li ng-repeat="result in results" md-highlight-text="searchTerm">
1682 function MdHighlight ($interpolate, $parse) {
1685 controller: 'MdHighlightCtrl',
1686 compile: function mdHighlightCompile(tElement, tAttr) {
1687 var termExpr = $parse(tAttr.mdHighlightText);
1688 var unsafeContentExpr = $interpolate(tElement.html());
1690 return function mdHighlightLink(scope, element, attr, ctrl) {
1691 ctrl.init(termExpr, unsafeContentExpr);
1697 })(window, window.angular);