You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1801 lines
57 KiB

7 years ago
  1. /*!
  2. * Angular Material Design
  3. * https://github.com/angular/material
  4. * @license MIT
  5. * v1.1.3
  6. */
  7. (function( window, angular, undefined ){
  8. "use strict";
  9. /**
  10. * @ngdoc module
  11. * @name material.components.chips
  12. */
  13. /*
  14. * @see js folder for chips implementation
  15. */
  16. angular.module('material.components.chips', [
  17. 'material.core',
  18. 'material.components.autocomplete'
  19. ]);
  20. MdChipCtrl['$inject'] = ["$scope", "$element", "$mdConstant", "$timeout", "$mdUtil"];angular
  21. .module('material.components.chips')
  22. .controller('MdChipCtrl', MdChipCtrl);
  23. /**
  24. * Controller for the MdChip component. Responsible for handling keyboard
  25. * events and editting the chip if needed.
  26. *
  27. * @param $scope
  28. * @param $element
  29. * @param $mdConstant
  30. * @param $timeout
  31. * @param $mdUtil
  32. * @constructor
  33. */
  34. function MdChipCtrl ($scope, $element, $mdConstant, $timeout, $mdUtil) {
  35. /**
  36. * @type {$scope}
  37. */
  38. this.$scope = $scope;
  39. /**
  40. * @type {$element}
  41. */
  42. this.$element = $element;
  43. /**
  44. * @type {$mdConstant}
  45. */
  46. this.$mdConstant = $mdConstant;
  47. /**
  48. * @type {$timeout}
  49. */
  50. this.$timeout = $timeout;
  51. /**
  52. * @type {$mdUtil}
  53. */
  54. this.$mdUtil = $mdUtil;
  55. /**
  56. * @type {boolean}
  57. */
  58. this.isEditting = false;
  59. /**
  60. * @type {MdChipsCtrl}
  61. */
  62. this.parentController = undefined;
  63. /**
  64. * @type {boolean}
  65. */
  66. this.enableChipEdit = false;
  67. }
  68. /**
  69. * @param {MdChipsCtrl} controller
  70. */
  71. MdChipCtrl.prototype.init = function(controller) {
  72. this.parentController = controller;
  73. this.enableChipEdit = this.parentController.enableChipEdit;
  74. if (this.enableChipEdit) {
  75. this.$element.on('keydown', this.chipKeyDown.bind(this));
  76. this.$element.on('mousedown', this.chipMouseDown.bind(this));
  77. this.getChipContent().addClass('_md-chip-content-edit-is-enabled');
  78. }
  79. };
  80. /**
  81. * @return {Object}
  82. */
  83. MdChipCtrl.prototype.getChipContent = function() {
  84. var chipContents = this.$element[0].getElementsByClassName('md-chip-content');
  85. return angular.element(chipContents[0]);
  86. };
  87. /**
  88. * @return {Object}
  89. */
  90. MdChipCtrl.prototype.getContentElement = function() {
  91. return angular.element(this.getChipContent().children()[0]);
  92. };
  93. /**
  94. * @return {number}
  95. */
  96. MdChipCtrl.prototype.getChipIndex = function() {
  97. return parseInt(this.$element.attr('index'));
  98. };
  99. /**
  100. * Presents an input element to edit the contents of the chip.
  101. */
  102. MdChipCtrl.prototype.goOutOfEditMode = function() {
  103. if (!this.isEditting) return;
  104. this.isEditting = false;
  105. this.$element.removeClass('_md-chip-editing');
  106. this.getChipContent()[0].contentEditable = 'false';
  107. var chipIndex = this.getChipIndex();
  108. var content = this.getContentElement().text();
  109. if (content) {
  110. this.parentController.updateChipContents(
  111. chipIndex,
  112. this.getContentElement().text()
  113. );
  114. this.$mdUtil.nextTick(function() {
  115. if (this.parentController.selectedChip === chipIndex) {
  116. this.parentController.focusChip(chipIndex);
  117. }
  118. }.bind(this));
  119. } else {
  120. this.parentController.removeChipAndFocusInput(chipIndex);
  121. }
  122. };
  123. /**
  124. * Given an HTML element. Selects contents of it.
  125. * @param node
  126. */
  127. MdChipCtrl.prototype.selectNodeContents = function(node) {
  128. var range, selection;
  129. if (document.body.createTextRange) {
  130. range = document.body.createTextRange();
  131. range.moveToElementText(node);
  132. range.select();
  133. } else if (window.getSelection) {
  134. selection = window.getSelection();
  135. range = document.createRange();
  136. range.selectNodeContents(node);
  137. selection.removeAllRanges();
  138. selection.addRange(range);
  139. }
  140. };
  141. /**
  142. * Presents an input element to edit the contents of the chip.
  143. */
  144. MdChipCtrl.prototype.goInEditMode = function() {
  145. this.isEditting = true;
  146. this.$element.addClass('_md-chip-editing');
  147. this.getChipContent()[0].contentEditable = 'true';
  148. this.getChipContent().on('blur', function() {
  149. this.goOutOfEditMode();
  150. }.bind(this));
  151. this.selectNodeContents(this.getChipContent()[0]);
  152. };
  153. /**
  154. * Handles the keydown event on the chip element. If enable-chip-edit attribute is
  155. * set to true, space or enter keys can trigger going into edit mode. Enter can also
  156. * trigger submitting if the chip is already being edited.
  157. * @param event
  158. */
  159. MdChipCtrl.prototype.chipKeyDown = function(event) {
  160. if (!this.isEditting &&
  161. (event.keyCode === this.$mdConstant.KEY_CODE.ENTER ||
  162. event.keyCode === this.$mdConstant.KEY_CODE.SPACE)) {
  163. event.preventDefault();
  164. this.goInEditMode();
  165. } else if (this.isEditting &&
  166. event.keyCode === this.$mdConstant.KEY_CODE.ENTER) {
  167. event.preventDefault();
  168. this.goOutOfEditMode();
  169. }
  170. };
  171. /**
  172. * Handles the double click event
  173. */
  174. MdChipCtrl.prototype.chipMouseDown = function() {
  175. if(this.getChipIndex() == this.parentController.selectedChip &&
  176. this.enableChipEdit &&
  177. !this.isEditting) {
  178. this.goInEditMode();
  179. }
  180. };
  181. MdChip['$inject'] = ["$mdTheming", "$mdUtil", "$compile", "$timeout"];angular
  182. .module('material.components.chips')
  183. .directive('mdChip', MdChip);
  184. /**
  185. * @ngdoc directive
  186. * @name mdChip
  187. * @module material.components.chips
  188. *
  189. * @description
  190. * `<md-chip>` is a component used within `<md-chips>` and is responsible for rendering individual
  191. * chips.
  192. *
  193. *
  194. * @usage
  195. * <hljs lang="html">
  196. * <md-chip>{{$chip}}</md-chip>
  197. * </hljs>
  198. *
  199. */
  200. // This hint text is hidden within a chip but used by screen readers to
  201. // inform the user how they can interact with a chip.
  202. var DELETE_HINT_TEMPLATE = '\
  203. <span ng-if="!$mdChipsCtrl.readonly" class="md-visually-hidden">\
  204. {{$mdChipsCtrl.deleteHint}}\
  205. </span>';
  206. /**
  207. * MDChip Directive Definition
  208. *
  209. * @param $mdTheming
  210. * @param $mdUtil
  211. * ngInject
  212. */
  213. function MdChip($mdTheming, $mdUtil, $compile, $timeout) {
  214. var deleteHintTemplate = $mdUtil.processTemplate(DELETE_HINT_TEMPLATE);
  215. return {
  216. restrict: 'E',
  217. require: ['^?mdChips', 'mdChip'],
  218. link: postLink,
  219. controller: 'MdChipCtrl'
  220. };
  221. function postLink(scope, element, attr, ctrls) {
  222. var chipsController = ctrls.shift();
  223. var chipController = ctrls.shift();
  224. var chipContentElement = angular.element(element[0].querySelector('.md-chip-content'));
  225. $mdTheming(element);
  226. if (chipsController) {
  227. chipController.init(chipsController);
  228. // Append our delete hint to the div.md-chip-content (which does not exist at compile time)
  229. chipContentElement.append($compile(deleteHintTemplate)(scope));
  230. // When a chip is blurred, make sure to unset (or reset) the selected chip so that tabbing
  231. // through elements works properly
  232. chipContentElement.on('blur', function() {
  233. chipsController.resetSelectedChip();
  234. chipsController.$scope.$applyAsync();
  235. });
  236. }
  237. // Use $timeout to ensure we run AFTER the element has been added to the DOM so we can focus it.
  238. $timeout(function() {
  239. if (!chipsController) {
  240. return;
  241. }
  242. if (chipsController.shouldFocusLastChip) {
  243. chipsController.focusLastChipThenInput();
  244. }
  245. });
  246. }
  247. }
  248. MdChipRemove['$inject'] = ["$timeout"];angular
  249. .module('material.components.chips')
  250. .directive('mdChipRemove', MdChipRemove);
  251. /**
  252. * @ngdoc directive
  253. * @name mdChipRemove
  254. * @restrict A
  255. * @module material.components.chips
  256. *
  257. * @description
  258. * Designates an element to be used as the delete button for a chip. <br/>
  259. * This element is passed as a child of the `md-chips` element.
  260. *
  261. * The designated button will be just appended to the chip and removes the given chip on click.<br/>
  262. * By default the button is not being styled by the `md-chips` component.
  263. *
  264. * @usage
  265. * <hljs lang="html">
  266. * <md-chips>
  267. * <button md-chip-remove="">
  268. * <md-icon md-svg-icon="md-close"></md-icon>
  269. * </button>
  270. * </md-chips>
  271. * </hljs>
  272. */
  273. /**
  274. * MdChipRemove Directive Definition.
  275. *
  276. * @param $timeout
  277. * @returns {{restrict: string, require: string[], link: Function, scope: boolean}}
  278. * @constructor
  279. */
  280. function MdChipRemove ($timeout) {
  281. return {
  282. restrict: 'A',
  283. require: '^mdChips',
  284. scope: false,
  285. link: postLink
  286. };
  287. function postLink(scope, element, attr, ctrl) {
  288. element.on('click', function(event) {
  289. scope.$apply(function() {
  290. ctrl.removeChip(scope.$$replacedScope.$index);
  291. });
  292. });
  293. // Child elements aren't available until after a $timeout tick as they are hidden by an
  294. // `ng-if`. see http://goo.gl/zIWfuw
  295. $timeout(function() {
  296. element.attr({ tabindex: -1, 'aria-hidden': true });
  297. element.find('button').attr('tabindex', '-1');
  298. });
  299. }
  300. }
  301. MdChipTransclude['$inject'] = ["$compile"];angular
  302. .module('material.components.chips')
  303. .directive('mdChipTransclude', MdChipTransclude);
  304. function MdChipTransclude ($compile) {
  305. return {
  306. restrict: 'EA',
  307. terminal: true,
  308. link: link,
  309. scope: false
  310. };
  311. function link (scope, element, attr) {
  312. var ctrl = scope.$parent.$mdChipsCtrl,
  313. newScope = ctrl.parent.$new(false, ctrl.parent);
  314. newScope.$$replacedScope = scope;
  315. newScope.$chip = scope.$chip;
  316. newScope.$index = scope.$index;
  317. newScope.$mdChipsCtrl = ctrl;
  318. var newHtml = ctrl.$scope.$eval(attr.mdChipTransclude);
  319. element.html(newHtml);
  320. $compile(element.contents())(newScope);
  321. }
  322. }
  323. /**
  324. * The default chip append delay.
  325. *
  326. * @type {number}
  327. */
  328. MdChipsCtrl['$inject'] = ["$scope", "$attrs", "$mdConstant", "$log", "$element", "$timeout", "$mdUtil"];
  329. var DEFAULT_CHIP_APPEND_DELAY = 300;
  330. angular
  331. .module('material.components.chips')
  332. .controller('MdChipsCtrl', MdChipsCtrl);
  333. /**
  334. * Controller for the MdChips component. Responsible for adding to and
  335. * removing from the list of chips, marking chips as selected, and binding to
  336. * the models of various input components.
  337. *
  338. * @param $scope
  339. * @param $attrs
  340. * @param $mdConstant
  341. * @param $log
  342. * @param $element
  343. * @param $timeout
  344. * @param $mdUtil
  345. * @constructor
  346. */
  347. function MdChipsCtrl ($scope, $attrs, $mdConstant, $log, $element, $timeout, $mdUtil) {
  348. /** @type {$timeout} **/
  349. this.$timeout = $timeout;
  350. /** @type {Object} */
  351. this.$mdConstant = $mdConstant;
  352. /** @type {angular.$scope} */
  353. this.$scope = $scope;
  354. /** @type {angular.$scope} */
  355. this.parent = $scope.$parent;
  356. /** @type {$mdUtil} */
  357. this.$mdUtil = $mdUtil;
  358. /** @type {$log} */
  359. this.$log = $log;
  360. /** @type {$element} */
  361. this.$element = $element;
  362. /** @type {$attrs} */
  363. this.$attrs = $attrs;
  364. /** @type {angular.NgModelController} */
  365. this.ngModelCtrl = null;
  366. /** @type {angular.NgModelController} */
  367. this.userInputNgModelCtrl = null;
  368. /** @type {MdAutocompleteCtrl} */
  369. this.autocompleteCtrl = null;
  370. /** @type {Element} */
  371. this.userInputElement = null;
  372. /** @type {Array.<Object>} */
  373. this.items = [];
  374. /** @type {number} */
  375. this.selectedChip = -1;
  376. /** @type {string} */
  377. this.enableChipEdit = $mdUtil.parseAttributeBoolean($attrs.mdEnableChipEdit);
  378. /** @type {string} */
  379. this.addOnBlur = $mdUtil.parseAttributeBoolean($attrs.mdAddOnBlur);
  380. /**
  381. * The text to be used as the aria-label for the input.
  382. * @type {string}
  383. */
  384. this.inputAriaLabel = 'Chips input.';
  385. /**
  386. * Hidden hint text to describe the chips container. Used to give context to screen readers when
  387. * the chips are readonly and the input cannot be selected.
  388. *
  389. * @type {string}
  390. */
  391. this.containerHint = 'Chips container. Use arrow keys to select chips.';
  392. /**
  393. * Hidden hint text for how to delete a chip. Used to give context to screen readers.
  394. * @type {string}
  395. */
  396. this.deleteHint = 'Press delete to remove this chip.';
  397. /**
  398. * Hidden label for the delete button. Used to give context to screen readers.
  399. * @type {string}
  400. */
  401. this.deleteButtonLabel = 'Remove';
  402. /**
  403. * Model used by the input element.
  404. * @type {string}
  405. */
  406. this.chipBuffer = '';
  407. /**
  408. * Whether to use the transformChip expression to transform the chip buffer
  409. * before appending it to the list.
  410. * @type {boolean}
  411. */
  412. this.useTransformChip = false;
  413. /**
  414. * Whether to use the onAdd expression to notify of chip additions.
  415. * @type {boolean}
  416. */
  417. this.useOnAdd = false;
  418. /**
  419. * Whether to use the onRemove expression to notify of chip removals.
  420. * @type {boolean}
  421. */
  422. this.useOnRemove = false;
  423. /**
  424. * The ID of the chips wrapper which is used to build unique IDs for the chips and the aria-owns
  425. * attribute.
  426. *
  427. * Defaults to '_md-chips-wrapper-' plus a unique number.
  428. *
  429. * @type {string}
  430. */
  431. this.wrapperId = '';
  432. /**
  433. * Array of unique numbers which will be auto-generated any time the items change, and is used to
  434. * create unique IDs for the aria-owns attribute.
  435. *
  436. * @type {Array}
  437. */
  438. this.contentIds = [];
  439. /**
  440. * The index of the chip that should have it's tabindex property set to 0 so it is selectable
  441. * via the keyboard.
  442. *
  443. * @type {int}
  444. */
  445. this.ariaTabIndex = null;
  446. /**
  447. * After appending a chip, the chip will be focused for this number of milliseconds before the
  448. * input is refocused.
  449. *
  450. * **Note:** This is **required** for compatibility with certain screen readers in order for
  451. * them to properly allow keyboard access.
  452. *
  453. * @type {number}
  454. */
  455. this.chipAppendDelay = DEFAULT_CHIP_APPEND_DELAY;
  456. this.init();
  457. }
  458. /**
  459. * Initializes variables and sets up watchers
  460. */
  461. MdChipsCtrl.prototype.init = function() {
  462. var ctrl = this;
  463. // Set the wrapper ID
  464. ctrl.wrapperId = '_md-chips-wrapper-' + ctrl.$mdUtil.nextUid();
  465. // Setup a watcher which manages the role and aria-owns attributes
  466. ctrl.$scope.$watchCollection('$mdChipsCtrl.items', function() {
  467. // Make sure our input and wrapper have the correct ARIA attributes
  468. ctrl.setupInputAria();
  469. ctrl.setupWrapperAria();
  470. });
  471. ctrl.$attrs.$observe('mdChipAppendDelay', function(newValue) {
  472. ctrl.chipAppendDelay = parseInt(newValue) || DEFAULT_CHIP_APPEND_DELAY;
  473. });
  474. };
  475. /**
  476. * If we have an input, ensure it has the appropriate ARIA attributes.
  477. */
  478. MdChipsCtrl.prototype.setupInputAria = function() {
  479. var input = this.$element.find('input');
  480. // If we have no input, just return
  481. if (!input) {
  482. return;
  483. }
  484. input.attr('role', 'textbox');
  485. input.attr('aria-multiline', true);
  486. };
  487. /**
  488. * Ensure our wrapper has the appropriate ARIA attributes.
  489. */
  490. MdChipsCtrl.prototype.setupWrapperAria = function() {
  491. var ctrl = this,
  492. wrapper = this.$element.find('md-chips-wrap');
  493. if (this.items && this.items.length) {
  494. // Dynamically add the listbox role on every change because it must be removed when there are
  495. // no items.
  496. wrapper.attr('role', 'listbox');
  497. // Generate some random (but unique) IDs for each chip
  498. this.contentIds = this.items.map(function() {
  499. return ctrl.wrapperId + '-chip-' + ctrl.$mdUtil.nextUid();
  500. });
  501. // Use the contentIDs above to generate the aria-owns attribute
  502. wrapper.attr('aria-owns', this.contentIds.join(' '));
  503. } else {
  504. // If we have no items, then the role and aria-owns attributes MUST be removed
  505. wrapper.removeAttr('role');
  506. wrapper.removeAttr('aria-owns');
  507. }
  508. };
  509. /**
  510. * Handles the keydown event on the input element: by default <enter> appends
  511. * the buffer to the chip list, while backspace removes the last chip in the
  512. * list if the current buffer is empty.
  513. * @param event
  514. */
  515. MdChipsCtrl.prototype.inputKeydown = function(event) {
  516. var chipBuffer = this.getChipBuffer();
  517. // If we have an autocomplete, and it handled the event, we have nothing to do
  518. if (this.autocompleteCtrl && event.isDefaultPrevented && event.isDefaultPrevented()) {
  519. return;
  520. }
  521. if (event.keyCode === this.$mdConstant.KEY_CODE.BACKSPACE) {
  522. // Only select and focus the previous chip, if the current caret position of the
  523. // input element is at the beginning.
  524. if (this.getCursorPosition(event.target) !== 0) {
  525. return;
  526. }
  527. event.preventDefault();
  528. event.stopPropagation();
  529. if (this.items.length) {
  530. this.selectAndFocusChipSafe(this.items.length - 1);
  531. }
  532. return;
  533. }
  534. // By default <enter> appends the buffer to the chip list.
  535. if (!this.separatorKeys || this.separatorKeys.length < 1) {
  536. this.separatorKeys = [this.$mdConstant.KEY_CODE.ENTER];
  537. }
  538. // Support additional separator key codes in an array of `md-separator-keys`.
  539. if (this.separatorKeys.indexOf(event.keyCode) !== -1) {
  540. if ((this.autocompleteCtrl && this.requireMatch) || !chipBuffer) return;
  541. event.preventDefault();
  542. // Only append the chip and reset the chip buffer if the max chips limit isn't reached.
  543. if (this.hasMaxChipsReached()) return;
  544. this.appendChip(chipBuffer.trim());
  545. this.resetChipBuffer();
  546. return false;
  547. }
  548. };
  549. /**
  550. * Returns the cursor position of the specified input element.
  551. * @param element HTMLInputElement
  552. * @returns {Number} Cursor Position of the input.
  553. */
  554. MdChipsCtrl.prototype.getCursorPosition = function(element) {
  555. /*
  556. * Figure out whether the current input for the chips buffer is valid for using
  557. * the selectionStart / end property to retrieve the cursor position.
  558. * Some browsers do not allow the use of those attributes, on different input types.
  559. */
  560. try {
  561. if (element.selectionStart === element.selectionEnd) {
  562. return element.selectionStart;
  563. }
  564. } catch (e) {
  565. if (!element.value) {
  566. return 0;
  567. }
  568. }
  569. };
  570. /**
  571. * Updates the content of the chip at given index
  572. * @param chipIndex
  573. * @param chipContents
  574. */
  575. MdChipsCtrl.prototype.updateChipContents = function(chipIndex, chipContents){
  576. if(chipIndex >= 0 && chipIndex < this.items.length) {
  577. this.items[chipIndex] = chipContents;
  578. this.ngModelCtrl.$setDirty();
  579. }
  580. };
  581. /**
  582. * Returns true if a chip is currently being edited. False otherwise.
  583. * @return {boolean}
  584. */
  585. MdChipsCtrl.prototype.isEditingChip = function() {
  586. return !!this.$element[0].querySelector('._md-chip-editing');
  587. };
  588. MdChipsCtrl.prototype.isRemovable = function() {
  589. // Return false if we have static chips
  590. if (!this.ngModelCtrl) {
  591. return false;
  592. }
  593. return this.readonly ? this.removable :
  594. angular.isDefined(this.removable) ? this.removable : true;
  595. };
  596. /**
  597. * Handles the keydown event on the chip elements: backspace removes the selected chip, arrow
  598. * keys switch which chips is active
  599. * @param event
  600. */
  601. MdChipsCtrl.prototype.chipKeydown = function (event) {
  602. if (this.getChipBuffer()) return;
  603. if (this.isEditingChip()) return;
  604. switch (event.keyCode) {
  605. case this.$mdConstant.KEY_CODE.BACKSPACE:
  606. case this.$mdConstant.KEY_CODE.DELETE:
  607. if (this.selectedChip < 0) return;
  608. event.preventDefault();
  609. // Cancel the delete action only after the event cancel. Otherwise the page will go back.
  610. if (!this.isRemovable()) return;
  611. this.removeAndSelectAdjacentChip(this.selectedChip);
  612. break;
  613. case this.$mdConstant.KEY_CODE.LEFT_ARROW:
  614. event.preventDefault();
  615. // By default, allow selection of -1 which will focus the input; if we're readonly, don't go
  616. // below 0
  617. if (this.selectedChip < 0 || (this.readonly && this.selectedChip == 0)) {
  618. this.selectedChip = this.items.length;
  619. }
  620. if (this.items.length) this.selectAndFocusChipSafe(this.selectedChip - 1);
  621. break;
  622. case this.$mdConstant.KEY_CODE.RIGHT_ARROW:
  623. event.preventDefault();
  624. this.selectAndFocusChipSafe(this.selectedChip + 1);
  625. break;
  626. case this.$mdConstant.KEY_CODE.ESCAPE:
  627. case this.$mdConstant.KEY_CODE.TAB:
  628. if (this.selectedChip < 0) return;
  629. event.preventDefault();
  630. this.onFocus();
  631. break;
  632. }
  633. };
  634. /**
  635. * Get the input's placeholder - uses `placeholder` when list is empty and `secondary-placeholder`
  636. * when the list is non-empty. If `secondary-placeholder` is not provided, `placeholder` is used
  637. * always.
  638. */
  639. MdChipsCtrl.prototype.getPlaceholder = function() {
  640. // Allow `secondary-placeholder` to be blank.
  641. var useSecondary = (this.items && this.items.length &&
  642. (this.secondaryPlaceholder == '' || this.secondaryPlaceholder));
  643. return useSecondary ? this.secondaryPlaceholder : this.placeholder;
  644. };
  645. /**
  646. * Removes chip at {@code index} and selects the adjacent chip.
  647. * @param index
  648. */
  649. MdChipsCtrl.prototype.removeAndSelectAdjacentChip = function(index) {
  650. var self = this;
  651. var selIndex = self.getAdjacentChipIndex(index);
  652. var wrap = this.$element[0].querySelector('md-chips-wrap');
  653. var chip = this.$element[0].querySelector('md-chip[index="' + index + '"]');
  654. self.removeChip(index);
  655. // The dobule-timeout is currently necessary to ensure that the DOM has finalized and the select()
  656. // will find the proper chip since the selection is index-based.
  657. //
  658. // TODO: Investigate calling from within chip $scope.$on('$destroy') to reduce/remove timeouts
  659. self.$timeout(function() {
  660. self.$timeout(function() {
  661. self.selectAndFocusChipSafe(selIndex);
  662. });
  663. });
  664. };
  665. /**
  666. * Sets the selected chip index to -1.
  667. */
  668. MdChipsCtrl.prototype.resetSelectedChip = function() {
  669. this.selectedChip = -1;
  670. this.ariaTabIndex = null;
  671. };
  672. /**
  673. * Gets the index of an adjacent chip to select after deletion. Adjacency is
  674. * determined as the next chip in the list, unless the target chip is the
  675. * last in the list, then it is the chip immediately preceding the target. If
  676. * there is only one item in the list, -1 is returned (select none).
  677. * The number returned is the index to select AFTER the target has been
  678. * removed.
  679. * If the current chip is not selected, then -1 is returned to select none.
  680. */
  681. MdChipsCtrl.prototype.getAdjacentChipIndex = function(index) {
  682. var len = this.items.length - 1;
  683. return (len == 0) ? -1 :
  684. (index == len) ? index -1 : index;
  685. };
  686. /**
  687. * Append the contents of the buffer to the chip list. This method will first
  688. * call out to the md-transform-chip method, if provided.
  689. *
  690. * @param newChip
  691. */
  692. MdChipsCtrl.prototype.appendChip = function(newChip) {
  693. this.shouldFocusLastChip = true;
  694. if (this.useTransformChip && this.transformChip) {
  695. var transformedChip = this.transformChip({'$chip': newChip});
  696. // Check to make sure the chip is defined before assigning it, otherwise, we'll just assume
  697. // they want the string version.
  698. if (angular.isDefined(transformedChip)) {
  699. newChip = transformedChip;
  700. }
  701. }
  702. // If items contains an identical object to newChip, do not append
  703. if (angular.isObject(newChip)){
  704. var identical = this.items.some(function(item){
  705. return angular.equals(newChip, item);
  706. });
  707. if (identical) return;
  708. }
  709. // Check for a null (but not undefined), or existing chip and cancel appending
  710. if (newChip == null || this.items.indexOf(newChip) + 1) return;
  711. // Append the new chip onto our list
  712. var length = this.items.push(newChip);
  713. var index = length - 1;
  714. // Update model validation
  715. this.ngModelCtrl.$setDirty();
  716. this.validateModel();
  717. // If they provide the md-on-add attribute, notify them of the chip addition
  718. if (this.useOnAdd && this.onAdd) {
  719. this.onAdd({ '$chip': newChip, '$index': index });
  720. }
  721. };
  722. /**
  723. * Sets whether to use the md-transform-chip expression. This expression is
  724. * bound to scope and controller in {@code MdChipsDirective} as
  725. * {@code transformChip}. Due to the nature of directive scope bindings, the
  726. * controller cannot know on its own/from the scope whether an expression was
  727. * actually provided.
  728. */
  729. MdChipsCtrl.prototype.useTransformChipExpression = function() {
  730. this.useTransformChip = true;
  731. };
  732. /**
  733. * Sets whether to use the md-on-add expression. This expression is
  734. * bound to scope and controller in {@code MdChipsDirective} as
  735. * {@code onAdd}. Due to the nature of directive scope bindings, the
  736. * controller cannot know on its own/from the scope whether an expression was
  737. * actually provided.
  738. */
  739. MdChipsCtrl.prototype.useOnAddExpression = function() {
  740. this.useOnAdd = true;
  741. };
  742. /**
  743. * Sets whether to use the md-on-remove expression. This expression is
  744. * bound to scope and controller in {@code MdChipsDirective} as
  745. * {@code onRemove}. Due to the nature of directive scope bindings, the
  746. * controller cannot know on its own/from the scope whether an expression was
  747. * actually provided.
  748. */
  749. MdChipsCtrl.prototype.useOnRemoveExpression = function() {
  750. this.useOnRemove = true;
  751. };
  752. /*
  753. * Sets whether to use the md-on-select expression. This expression is
  754. * bound to scope and controller in {@code MdChipsDirective} as
  755. * {@code onSelect}. Due to the nature of directive scope bindings, the
  756. * controller cannot know on its own/from the scope whether an expression was
  757. * actually provided.
  758. */
  759. MdChipsCtrl.prototype.useOnSelectExpression = function() {
  760. this.useOnSelect = true;
  761. };
  762. /**
  763. * Gets the input buffer. The input buffer can be the model bound to the
  764. * default input item {@code this.chipBuffer}, the {@code selectedItem}
  765. * model of an {@code md-autocomplete}, or, through some magic, the model
  766. * bound to any inpput or text area element found within a
  767. * {@code md-input-container} element.
  768. * @return {string}
  769. */
  770. MdChipsCtrl.prototype.getChipBuffer = function() {
  771. var chipBuffer = !this.userInputElement ? this.chipBuffer :
  772. this.userInputNgModelCtrl ? this.userInputNgModelCtrl.$viewValue :
  773. this.userInputElement[0].value;
  774. // Ensure that the chip buffer is always a string. For example, the input element buffer might be falsy.
  775. return angular.isString(chipBuffer) ? chipBuffer : '';
  776. };
  777. /**
  778. * Resets the input buffer for either the internal input or user provided input element.
  779. */
  780. MdChipsCtrl.prototype.resetChipBuffer = function() {
  781. if (this.userInputElement) {
  782. if (this.userInputNgModelCtrl) {
  783. this.userInputNgModelCtrl.$setViewValue('');
  784. this.userInputNgModelCtrl.$render();
  785. } else {
  786. this.userInputElement[0].value = '';
  787. }
  788. } else {
  789. this.chipBuffer = '';
  790. }
  791. };
  792. MdChipsCtrl.prototype.hasMaxChipsReached = function() {
  793. if (angular.isString(this.maxChips)) this.maxChips = parseInt(this.maxChips, 10) || 0;
  794. return this.maxChips > 0 && this.items.length >= this.maxChips;
  795. };
  796. /**
  797. * Updates the validity properties for the ngModel.
  798. */
  799. MdChipsCtrl.prototype.validateModel = function() {
  800. this.ngModelCtrl.$setValidity('md-max-chips', !this.hasMaxChipsReached());
  801. };
  802. /**
  803. * Removes the chip at the given index.
  804. * @param index
  805. */
  806. MdChipsCtrl.prototype.removeChip = function(index) {
  807. var removed = this.items.splice(index, 1);
  808. // Update model validation
  809. this.ngModelCtrl.$setDirty();
  810. this.validateModel();
  811. if (removed && removed.length && this.useOnRemove && this.onRemove) {
  812. this.onRemove({ '$chip': removed[0], '$index': index });
  813. }
  814. };
  815. MdChipsCtrl.prototype.removeChipAndFocusInput = function (index) {
  816. this.removeChip(index);
  817. if (this.autocompleteCtrl) {
  818. // Always hide the autocomplete dropdown before focusing the autocomplete input.
  819. // Wait for the input to move horizontally, because the chip was removed.
  820. // This can lead to an incorrect dropdown position.
  821. this.autocompleteCtrl.hidden = true;
  822. this.$mdUtil.nextTick(this.onFocus.bind(this));
  823. } else {
  824. this.onFocus();
  825. }
  826. };
  827. /**
  828. * Selects the chip at `index`,
  829. * @param index
  830. */
  831. MdChipsCtrl.prototype.selectAndFocusChipSafe = function(index) {
  832. // If we have no chips, or are asked to select a chip before the first, just focus the input
  833. if (!this.items.length || index === -1) {
  834. return this.focusInput();
  835. }
  836. // If we are asked to select a chip greater than the number of chips...
  837. if (index >= this.items.length) {
  838. if (this.readonly) {
  839. // If we are readonly, jump back to the start (because we have no input)
  840. index = 0;
  841. } else {
  842. // If we are not readonly, we should attempt to focus the input
  843. return this.onFocus();
  844. }
  845. }
  846. index = Math.max(index, 0);
  847. index = Math.min(index, this.items.length - 1);
  848. this.selectChip(index);
  849. this.focusChip(index);
  850. };
  851. MdChipsCtrl.prototype.focusLastChipThenInput = function() {
  852. var ctrl = this;
  853. ctrl.shouldFocusLastChip = false;
  854. ctrl.focusChip(this.items.length - 1);
  855. ctrl.$timeout(function() {
  856. ctrl.focusInput();
  857. }, ctrl.chipAppendDelay);
  858. };
  859. MdChipsCtrl.prototype.focusInput = function() {
  860. this.selectChip(-1);
  861. this.onFocus();
  862. };
  863. /**
  864. * Marks the chip at the given index as selected.
  865. * @param index
  866. */
  867. MdChipsCtrl.prototype.selectChip = function(index) {
  868. if (index >= -1 && index <= this.items.length) {
  869. this.selectedChip = index;
  870. // Fire the onSelect if provided
  871. if (this.useOnSelect && this.onSelect) {
  872. this.onSelect({'$chip': this.items[index] });
  873. }
  874. } else {
  875. this.$log.warn('Selected Chip index out of bounds; ignoring.');
  876. }
  877. };
  878. /**
  879. * Selects the chip at `index` and gives it focus.
  880. * @param index
  881. */
  882. MdChipsCtrl.prototype.selectAndFocusChip = function(index) {
  883. this.selectChip(index);
  884. if (index != -1) {
  885. this.focusChip(index);
  886. }
  887. };
  888. /**
  889. * Call `focus()` on the chip at `index`
  890. */
  891. MdChipsCtrl.prototype.focusChip = function(index) {
  892. var chipContent = this.$element[0].querySelector('md-chip[index="' + index + '"] .md-chip-content');
  893. this.ariaTabIndex = index;
  894. chipContent.focus();
  895. };
  896. /**
  897. * Configures the required interactions with the ngModel Controller.
  898. * Specifically, set {@code this.items} to the {@code NgModelCtrl#$viewVale}.
  899. * @param ngModelCtrl
  900. */
  901. MdChipsCtrl.prototype.configureNgModel = function(ngModelCtrl) {
  902. this.ngModelCtrl = ngModelCtrl;
  903. var self = this;
  904. ngModelCtrl.$render = function() {
  905. // model is updated. do something.
  906. self.items = self.ngModelCtrl.$viewValue;
  907. };
  908. };
  909. MdChipsCtrl.prototype.onFocus = function () {
  910. var input = this.$element[0].querySelector('input');
  911. input && input.focus();
  912. this.resetSelectedChip();
  913. };
  914. MdChipsCtrl.prototype.onInputFocus = function () {
  915. this.inputHasFocus = true;
  916. // Make sure we have the appropriate ARIA attributes
  917. this.setupInputAria();
  918. // Make sure we don't have any chips selected
  919. this.resetSelectedChip();
  920. };
  921. MdChipsCtrl.prototype.onInputBlur = function () {
  922. this.inputHasFocus = false;
  923. if (this.shouldAddOnBlur()) {
  924. this.appendChip(this.getChipBuffer().trim());
  925. this.resetChipBuffer();
  926. }
  927. };
  928. /**
  929. * Configure event bindings on a user-provided input element.
  930. * @param inputElement
  931. */
  932. MdChipsCtrl.prototype.configureUserInput = function(inputElement) {
  933. this.userInputElement = inputElement;
  934. // Find the NgModelCtrl for the input element
  935. var ngModelCtrl = inputElement.controller('ngModel');
  936. // `.controller` will look in the parent as well.
  937. if (ngModelCtrl != this.ngModelCtrl) {
  938. this.userInputNgModelCtrl = ngModelCtrl;
  939. }
  940. var scope = this.$scope;
  941. var ctrl = this;
  942. // Run all of the events using evalAsync because a focus may fire a blur in the same digest loop
  943. var scopeApplyFn = function(event, fn) {
  944. scope.$evalAsync(angular.bind(ctrl, fn, event));
  945. };
  946. // Bind to keydown and focus events of input
  947. inputElement
  948. .attr({ tabindex: 0 })
  949. .on('keydown', function(event) { scopeApplyFn(event, ctrl.inputKeydown) })
  950. .on('focus', function(event) { scopeApplyFn(event, ctrl.onInputFocus) })
  951. .on('blur', function(event) { scopeApplyFn(event, ctrl.onInputBlur) })
  952. };
  953. MdChipsCtrl.prototype.configureAutocomplete = function(ctrl) {
  954. if (ctrl) {
  955. this.autocompleteCtrl = ctrl;
  956. ctrl.registerSelectedItemWatcher(angular.bind(this, function (item) {
  957. if (item) {
  958. // Only append the chip and reset the chip buffer if the max chips limit isn't reached.
  959. if (this.hasMaxChipsReached()) return;
  960. this.appendChip(item);
  961. this.resetChipBuffer();
  962. }
  963. }));
  964. this.$element.find('input')
  965. .on('focus',angular.bind(this, this.onInputFocus) )
  966. .on('blur', angular.bind(this, this.onInputBlur) );
  967. }
  968. };
  969. /**
  970. * Whether the current chip buffer should be added on input blur or not.
  971. * @returns {boolean}
  972. */
  973. MdChipsCtrl.prototype.shouldAddOnBlur = function() {
  974. // Update the custom ngModel validators from the chips component.
  975. this.validateModel();
  976. var chipBuffer = this.getChipBuffer().trim();
  977. var isModelValid = this.ngModelCtrl.$valid;
  978. var isAutocompleteShowing = this.autocompleteCtrl && !this.autocompleteCtrl.hidden;
  979. if (this.userInputNgModelCtrl) {
  980. isModelValid = isModelValid && this.userInputNgModelCtrl.$valid;
  981. }
  982. return this.addOnBlur && !this.requireMatch && chipBuffer && isModelValid && !isAutocompleteShowing;
  983. };
  984. MdChipsCtrl.prototype.hasFocus = function () {
  985. return this.inputHasFocus || this.selectedChip >= 0;
  986. };
  987. MdChipsCtrl.prototype.contentIdFor = function(index) {
  988. return this.contentIds[index];
  989. };
  990. MdChips['$inject'] = ["$mdTheming", "$mdUtil", "$compile", "$log", "$timeout", "$$mdSvgRegistry"];angular
  991. .module('material.components.chips')
  992. .directive('mdChips', MdChips);
  993. /**
  994. * @ngdoc directive
  995. * @name mdChips
  996. * @module material.components.chips
  997. *
  998. * @description
  999. * `<md-chips>` is an input component for building lists of strings or objects. The list items are
  1000. * displayed as 'chips'. This component can make use of an `<input>` element or an
  1001. * `<md-autocomplete>` element.
  1002. *
  1003. * ### Custom templates
  1004. * A custom template may be provided to render the content of each chip. This is achieved by
  1005. * specifying an `<md-chip-template>` element containing the custom content as a child of
  1006. * `<md-chips>`.
  1007. *
  1008. * Note: Any attributes on
  1009. * `<md-chip-template>` will be dropped as only the innerHTML is used for the chip template. The
  1010. * variables `$chip` and `$index` are available in the scope of `<md-chip-template>`, representing
  1011. * the chip object and its index in the list of chips, respectively.
  1012. * To override the chip delete control, include an element (ideally a button) with the attribute
  1013. * `md-chip-remove`. A click listener to remove the chip will be added automatically. The element
  1014. * is also placed as a sibling to the chip content (on which there are also click listeners) to
  1015. * avoid a nested ng-click situation.
  1016. *
  1017. * <!-- Note: We no longer want to include this in the site docs; but it should remain here for
  1018. * future developers and those looking at the documentation.
  1019. *
  1020. * <h3> Pending Features </h3>
  1021. * <ul style="padding-left:20px;">
  1022. *
  1023. * <ul>Style
  1024. * <li>Colours for hover, press states (ripple?).</li>
  1025. * </ul>
  1026. *
  1027. * <ul>Validation
  1028. * <li>allow a validation callback</li>
  1029. * <li>hilighting style for invalid chips</li>
  1030. * </ul>
  1031. *
  1032. * <ul>Item mutation
  1033. * <li>Support `
  1034. * <md-chip-edit>` template, show/hide the edit element on tap/click? double tap/double
  1035. * click?
  1036. * </li>
  1037. * </ul>
  1038. *
  1039. * <ul>Truncation and Disambiguation (?)
  1040. * <li>Truncate chip text where possible, but do not truncate entries such that two are
  1041. * indistinguishable.</li>
  1042. * </ul>
  1043. *
  1044. * <ul>Drag and Drop
  1045. * <li>Drag and drop chips between related `<md-chips>` elements.
  1046. * </li>
  1047. * </ul>
  1048. * </ul>
  1049. *
  1050. * //-->
  1051. *
  1052. * Sometimes developers want to limit the amount of possible chips.<br/>
  1053. * You can specify the maximum amount of chips by using the following markup.
  1054. *
  1055. * <hljs lang="html">
  1056. * <md-chips
  1057. * ng-model="myItems"
  1058. * placeholder="Add an item"
  1059. * md-max-chips="5">
  1060. * </md-chips>
  1061. * </hljs>
  1062. *
  1063. * In some cases, you have an autocomplete inside of the `md-chips`.<br/>
  1064. * When the maximum amount of chips has been reached, you can also disable the autocomplete selection.<br/>
  1065. * Here is an example markup.
  1066. *
  1067. * <hljs lang="html">
  1068. * <md-chips ng-model="myItems" md-max-chips="5">
  1069. * <md-autocomplete ng-hide="myItems.length > 5" ...></md-autocomplete>
  1070. * </md-chips>
  1071. * </hljs>
  1072. *
  1073. * ### Accessibility
  1074. *
  1075. * The `md-chips` component supports keyboard and screen reader users since Version 1.1.2. In
  1076. * order to achieve this, we modified the chips behavior to select newly appended chips for
  1077. * `300ms` before re-focusing the input and allowing the user to type.
  1078. *
  1079. * For most users, this delay is small enough that it will not be noticeable but allows certain
  1080. * screen readers to function properly (JAWS and NVDA in particular).
  1081. *
  1082. * We introduced a new `md-chip-append-delay` option to allow developers to better control this
  1083. * behavior.
  1084. *
  1085. * Please refer to the documentation of this option (below) for more information.
  1086. *
  1087. * @param {string=|object=} ng-model A model to which the list of items will be bound.
  1088. * @param {string=} placeholder Placeholder text that will be forwarded to the input.
  1089. * @param {string=} secondary-placeholder Placeholder text that will be forwarded to the input,
  1090. * displayed when there is at least one item in the list
  1091. * @param {boolean=} md-removable Enables or disables the deletion of chips through the
  1092. * removal icon or the Delete/Backspace key. Defaults to true.
  1093. * @param {boolean=} readonly Disables list manipulation (deleting or adding list items), hiding
  1094. * the input and delete buttons. If no `ng-model` is provided, the chips will automatically be
  1095. * marked as readonly.<br/><br/>
  1096. * When `md-removable` is not defined, the `md-remove` behavior will be overwritten and disabled.
  1097. * @param {string=} md-enable-chip-edit Set this to "true" to enable editing of chip contents. The user can
  1098. * go into edit mode with pressing "space", "enter", or double clicking on the chip. Chip edit is only
  1099. * supported for chips with basic template.
  1100. * @param {number=} md-max-chips The maximum number of chips allowed to add through user input.
  1101. * <br/><br/>The validation property `md-max-chips` can be used when the max chips
  1102. * amount is reached.
  1103. * @param {boolean=} md-add-on-blur When set to true, remaining text inside of the input will
  1104. * be converted into a new chip on blur.
  1105. * @param {expression} md-transform-chip An expression of form `myFunction($chip)` that when called
  1106. * expects one of the following return values:
  1107. * - an object representing the `$chip` input string
  1108. * - `undefined` to simply add the `$chip` input string, or
  1109. * - `null` to prevent the chip from being appended
  1110. * @param {expression=} md-on-add An expression which will be called when a chip has been
  1111. * added.
  1112. * @param {expression=} md-on-remove An expression which will be called when a chip has been
  1113. * removed.
  1114. * @param {expression=} md-on-select An expression which will be called when a chip is selected.
  1115. * @param {boolean} md-require-match If true, and the chips template contains an autocomplete,
  1116. * only allow selection of pre-defined chips (i.e. you cannot add new ones).
  1117. * @param {string=} input-aria-label A string read by screen readers to identify the input.
  1118. * @param {string=} container-hint A string read by screen readers informing users of how to
  1119. * navigate the chips. Used in readonly mode.
  1120. * @param {string=} delete-hint A string read by screen readers instructing users that pressing
  1121. * the delete key will remove the chip.
  1122. * @param {string=} delete-button-label A label for the delete button. Also hidden and read by
  1123. * screen readers.
  1124. * @param {expression=} md-separator-keys An array of key codes used to separate chips.
  1125. * @param {string=} md-chip-append-delay The number of milliseconds that the component will select
  1126. * a newly appended chip before allowing a user to type into the input. This is **necessary**
  1127. * for keyboard accessibility for screen readers. It defaults to 300ms and any number less than
  1128. * 300 can cause issues with screen readers (particularly JAWS and sometimes NVDA).
  1129. *
  1130. * _Available since Version 1.1.2._
  1131. *
  1132. * **Note:** You can safely set this to `0` in one of the following two instances:
  1133. *
  1134. * 1. You are targeting an iOS or Safari-only application (where users would use VoiceOver) or
  1135. * only ChromeVox users.
  1136. *
  1137. * 2. If you have utilized the `md-separator-keys` to disable the `enter` keystroke in
  1138. * favor of another one (such as `,` or `;`).
  1139. *
  1140. * @usage
  1141. * <hljs lang="html">
  1142. * <md-chips
  1143. * ng-model="myItems"
  1144. * placeholder="Add an item"
  1145. * readonly="isReadOnly">
  1146. * </md-chips>
  1147. * </hljs>
  1148. *
  1149. * <h3>Validation</h3>
  1150. * When using [ngMessages](https://docs.angularjs.org/api/ngMessages), you can show errors based
  1151. * on our custom validators.
  1152. * <hljs lang="html">
  1153. * <form name="userForm">
  1154. * <md-chips
  1155. * name="fruits"
  1156. * ng-model="myItems"
  1157. * placeholder="Add an item"
  1158. * md-max-chips="5">
  1159. * </md-chips>
  1160. * <div ng-messages="userForm.fruits.$error" ng-if="userForm.$dirty">
  1161. * <div ng-message="md-max-chips">You reached the maximum amount of chips</div>
  1162. * </div>
  1163. * </form>
  1164. * </hljs>
  1165. *
  1166. */
  1167. var MD_CHIPS_TEMPLATE = '\
  1168. <md-chips-wrap\
  1169. id="{{$mdChipsCtrl.wrapperId}}"\
  1170. tabindex="{{$mdChipsCtrl.readonly ? 0 : -1}}"\
  1171. ng-keydown="$mdChipsCtrl.chipKeydown($event)"\
  1172. ng-class="{ \'md-focused\': $mdChipsCtrl.hasFocus(), \
  1173. \'md-readonly\': !$mdChipsCtrl.ngModelCtrl || $mdChipsCtrl.readonly,\
  1174. \'md-removable\': $mdChipsCtrl.isRemovable() }"\
  1175. aria-setsize="{{$mdChipsCtrl.items.length}}"\
  1176. class="md-chips">\
  1177. <span ng-if="$mdChipsCtrl.readonly" class="md-visually-hidden">\
  1178. {{$mdChipsCtrl.containerHint}}\
  1179. </span>\
  1180. <md-chip ng-repeat="$chip in $mdChipsCtrl.items"\
  1181. index="{{$index}}"\
  1182. ng-class="{\'md-focused\': $mdChipsCtrl.selectedChip == $index, \'md-readonly\': !$mdChipsCtrl.ngModelCtrl || $mdChipsCtrl.readonly}">\
  1183. <div class="md-chip-content"\
  1184. tabindex="{{$mdChipsCtrl.ariaTabIndex == $index ? 0 : -1}}"\
  1185. id="{{$mdChipsCtrl.contentIdFor($index)}}"\
  1186. role="option"\
  1187. aria-selected="{{$mdChipsCtrl.selectedChip == $index}}" \
  1188. aria-posinset="{{$index}}"\
  1189. ng-click="!$mdChipsCtrl.readonly && $mdChipsCtrl.focusChip($index)"\
  1190. ng-focus="!$mdChipsCtrl.readonly && $mdChipsCtrl.selectChip($index)"\
  1191. md-chip-transclude="$mdChipsCtrl.chipContentsTemplate"></div>\
  1192. <div ng-if="$mdChipsCtrl.isRemovable()"\
  1193. class="md-chip-remove-container"\
  1194. tabindex="-1"\
  1195. md-chip-transclude="$mdChipsCtrl.chipRemoveTemplate"></div>\
  1196. </md-chip>\
  1197. <div class="md-chip-input-container" ng-if="!$mdChipsCtrl.readonly && $mdChipsCtrl.ngModelCtrl">\
  1198. <div md-chip-transclude="$mdChipsCtrl.chipInputTemplate"></div>\
  1199. </div>\
  1200. </md-chips-wrap>';
  1201. var CHIP_INPUT_TEMPLATE = '\
  1202. <input\
  1203. class="md-input"\
  1204. tabindex="0"\
  1205. aria-label="{{$mdChipsCtrl.inputAriaLabel}}" \
  1206. placeholder="{{$mdChipsCtrl.getPlaceholder()}}"\
  1207. ng-model="$mdChipsCtrl.chipBuffer"\
  1208. ng-focus="$mdChipsCtrl.onInputFocus()"\
  1209. ng-blur="$mdChipsCtrl.onInputBlur()"\
  1210. ng-keydown="$mdChipsCtrl.inputKeydown($event)">';
  1211. var CHIP_DEFAULT_TEMPLATE = '\
  1212. <span>{{$chip}}</span>';
  1213. var CHIP_REMOVE_TEMPLATE = '\
  1214. <button\
  1215. class="md-chip-remove"\
  1216. ng-if="$mdChipsCtrl.isRemovable()"\
  1217. ng-click="$mdChipsCtrl.removeChipAndFocusInput($$replacedScope.$index)"\
  1218. type="button"\
  1219. tabindex="-1">\
  1220. <md-icon md-svg-src="{{ $mdChipsCtrl.mdCloseIcon }}"></md-icon>\
  1221. <span class="md-visually-hidden">\
  1222. {{$mdChipsCtrl.deleteButtonLabel}}\
  1223. </span>\
  1224. </button>';
  1225. /**
  1226. * MDChips Directive Definition
  1227. */
  1228. function MdChips ($mdTheming, $mdUtil, $compile, $log, $timeout, $$mdSvgRegistry) {
  1229. // Run our templates through $mdUtil.processTemplate() to allow custom start/end symbols
  1230. var templates = getTemplates();
  1231. return {
  1232. template: function(element, attrs) {
  1233. // Clone the element into an attribute. By prepending the attribute
  1234. // name with '$', Angular won't write it into the DOM. The cloned
  1235. // element propagates to the link function via the attrs argument,
  1236. // where various contained-elements can be consumed.
  1237. attrs['$mdUserTemplate'] = element.clone();
  1238. return templates.chips;
  1239. },
  1240. require: ['mdChips'],
  1241. restrict: 'E',
  1242. controller: 'MdChipsCtrl',
  1243. controllerAs: '$mdChipsCtrl',
  1244. bindToController: true,
  1245. compile: compile,
  1246. scope: {
  1247. readonly: '=readonly',
  1248. removable: '=mdRemovable',
  1249. placeholder: '@',
  1250. secondaryPlaceholder: '@',
  1251. maxChips: '@mdMaxChips',
  1252. transformChip: '&mdTransformChip',
  1253. onAppend: '&mdOnAppend',
  1254. onAdd: '&mdOnAdd',
  1255. onRemove: '&mdOnRemove',
  1256. onSelect: '&mdOnSelect',
  1257. inputAriaLabel: '@',
  1258. containerHint: '@',
  1259. deleteHint: '@',
  1260. deleteButtonLabel: '@',
  1261. separatorKeys: '=?mdSeparatorKeys',
  1262. requireMatch: '=?mdRequireMatch',
  1263. chipAppendDelayString: '@?mdChipAppendDelay'
  1264. }
  1265. };
  1266. /**
  1267. * Builds the final template for `md-chips` and returns the postLink function.
  1268. *
  1269. * Building the template involves 3 key components:
  1270. * static chips
  1271. * chip template
  1272. * input control
  1273. *
  1274. * If no `ng-model` is provided, only the static chip work needs to be done.
  1275. *
  1276. * If no user-passed `md-chip-template` exists, the default template is used. This resulting
  1277. * template is appended to the chip content element.
  1278. *
  1279. * The remove button may be overridden by passing an element with an md-chip-remove attribute.
  1280. *
  1281. * If an `input` or `md-autocomplete` element is provided by the caller, it is set aside for
  1282. * transclusion later. The transclusion happens in `postLink` as the parent scope is required.
  1283. * If no user input is provided, a default one is appended to the input container node in the
  1284. * template.
  1285. *
  1286. * Static Chips (i.e. `md-chip` elements passed from the caller) are gathered and set aside for
  1287. * transclusion in the `postLink` function.
  1288. *
  1289. *
  1290. * @param element
  1291. * @param attr
  1292. * @returns {Function}
  1293. */
  1294. function compile(element, attr) {
  1295. // Grab the user template from attr and reset the attribute to null.
  1296. var userTemplate = attr['$mdUserTemplate'];
  1297. attr['$mdUserTemplate'] = null;
  1298. var chipTemplate = getTemplateByQuery('md-chips>md-chip-template');
  1299. var chipRemoveSelector = $mdUtil
  1300. .prefixer()
  1301. .buildList('md-chip-remove')
  1302. .map(function(attr) {
  1303. return 'md-chips>*[' + attr + ']';
  1304. })
  1305. .join(',');
  1306. // Set the chip remove, chip contents and chip input templates. The link function will put
  1307. // them on the scope for transclusion later.
  1308. var chipRemoveTemplate = getTemplateByQuery(chipRemoveSelector) || templates.remove,
  1309. chipContentsTemplate = chipTemplate || templates.default,
  1310. chipInputTemplate = getTemplateByQuery('md-chips>md-autocomplete')
  1311. || getTemplateByQuery('md-chips>input')
  1312. || templates.input,
  1313. staticChips = userTemplate.find('md-chip');
  1314. // Warn of malformed template. See #2545
  1315. if (userTemplate[0].querySelector('md-chip-template>*[md-chip-remove]')) {
  1316. $log.warn('invalid placement of md-chip-remove within md-chip-template.');
  1317. }
  1318. function getTemplateByQuery (query) {
  1319. if (!attr.ngModel) return;
  1320. var element = userTemplate[0].querySelector(query);
  1321. return element && element.outerHTML;
  1322. }
  1323. /**
  1324. * Configures controller and transcludes.
  1325. */
  1326. return function postLink(scope, element, attrs, controllers) {
  1327. $mdUtil.initOptionalProperties(scope, attr);
  1328. $mdTheming(element);
  1329. var mdChipsCtrl = controllers[0];
  1330. if(chipTemplate) {
  1331. // Chip editing functionality assumes we are using the default chip template.
  1332. mdChipsCtrl.enableChipEdit = false;
  1333. }
  1334. mdChipsCtrl.chipContentsTemplate = chipContentsTemplate;
  1335. mdChipsCtrl.chipRemoveTemplate = chipRemoveTemplate;
  1336. mdChipsCtrl.chipInputTemplate = chipInputTemplate;
  1337. mdChipsCtrl.mdCloseIcon = $$mdSvgRegistry.mdClose;
  1338. element
  1339. .attr({ tabindex: -1 })
  1340. .on('focus', function () { mdChipsCtrl.onFocus(); });
  1341. if (attr.ngModel) {
  1342. mdChipsCtrl.configureNgModel(element.controller('ngModel'));
  1343. // If an `md-transform-chip` attribute was set, tell the controller to use the expression
  1344. // before appending chips.
  1345. if (attrs.mdTransformChip) mdChipsCtrl.useTransformChipExpression();
  1346. // If an `md-on-append` attribute was set, tell the controller to use the expression
  1347. // when appending chips.
  1348. //
  1349. // DEPRECATED: Will remove in official 1.0 release
  1350. if (attrs.mdOnAppend) mdChipsCtrl.useOnAppendExpression();
  1351. // If an `md-on-add` attribute was set, tell the controller to use the expression
  1352. // when adding chips.
  1353. if (attrs.mdOnAdd) mdChipsCtrl.useOnAddExpression();
  1354. // If an `md-on-remove` attribute was set, tell the controller to use the expression
  1355. // when removing chips.
  1356. if (attrs.mdOnRemove) mdChipsCtrl.useOnRemoveExpression();
  1357. // If an `md-on-select` attribute was set, tell the controller to use the expression
  1358. // when selecting chips.
  1359. if (attrs.mdOnSelect) mdChipsCtrl.useOnSelectExpression();
  1360. // The md-autocomplete and input elements won't be compiled until after this directive
  1361. // is complete (due to their nested nature). Wait a tick before looking for them to
  1362. // configure the controller.
  1363. if (chipInputTemplate != templates.input) {
  1364. // The autocomplete will not appear until the readonly attribute is not true (i.e.
  1365. // false or undefined), so we have to watch the readonly and then on the next tick
  1366. // after the chip transclusion has run, we can configure the autocomplete and user
  1367. // input.
  1368. scope.$watch('$mdChipsCtrl.readonly', function(readonly) {
  1369. if (!readonly) {
  1370. $mdUtil.nextTick(function(){
  1371. if (chipInputTemplate.indexOf('<md-autocomplete') === 0) {
  1372. var autocompleteEl = element.find('md-autocomplete');
  1373. mdChipsCtrl.configureAutocomplete(autocompleteEl.controller('mdAutocomplete'));
  1374. }
  1375. mdChipsCtrl.configureUserInput(element.find('input'));
  1376. });
  1377. }
  1378. });
  1379. }
  1380. // At the next tick, if we find an input, make sure it has the md-input class
  1381. $mdUtil.nextTick(function() {
  1382. var input = element.find('input');
  1383. input && input.toggleClass('md-input', true);
  1384. });
  1385. }
  1386. // Compile with the parent's scope and prepend any static chips to the wrapper.
  1387. if (staticChips.length > 0) {
  1388. var compiledStaticChips = $compile(staticChips.clone())(scope.$parent);
  1389. $timeout(function() { element.find('md-chips-wrap').prepend(compiledStaticChips); });
  1390. }
  1391. };
  1392. }
  1393. function getTemplates() {
  1394. return {
  1395. chips: $mdUtil.processTemplate(MD_CHIPS_TEMPLATE),
  1396. input: $mdUtil.processTemplate(CHIP_INPUT_TEMPLATE),
  1397. default: $mdUtil.processTemplate(CHIP_DEFAULT_TEMPLATE),
  1398. remove: $mdUtil.processTemplate(CHIP_REMOVE_TEMPLATE)
  1399. };
  1400. }
  1401. }
  1402. angular
  1403. .module('material.components.chips')
  1404. .controller('MdContactChipsCtrl', MdContactChipsCtrl);
  1405. /**
  1406. * Controller for the MdContactChips component
  1407. * @constructor
  1408. */
  1409. function MdContactChipsCtrl () {
  1410. /** @type {Object} */
  1411. this.selectedItem = null;
  1412. /** @type {string} */
  1413. this.searchText = '';
  1414. }
  1415. MdContactChipsCtrl.prototype.queryContact = function(searchText) {
  1416. return this.contactQuery({'$query': searchText});
  1417. };
  1418. MdContactChipsCtrl.prototype.itemName = function(item) {
  1419. return item[this.contactName];
  1420. };
  1421. MdContactChips['$inject'] = ["$mdTheming", "$mdUtil"];angular
  1422. .module('material.components.chips')
  1423. .directive('mdContactChips', MdContactChips);
  1424. /**
  1425. * @ngdoc directive
  1426. * @name mdContactChips
  1427. * @module material.components.chips
  1428. *
  1429. * @description
  1430. * `<md-contact-chips>` is an input component based on `md-chips` and makes use of an
  1431. * `md-autocomplete` element. The component allows the caller to supply a query expression which
  1432. * returns a list of possible contacts. The user can select one of these and add it to the list of
  1433. * chips.
  1434. *
  1435. * You may also use the `md-highlight-text` directive along with its parameters to control the
  1436. * appearance of the matched text inside of the contacts' autocomplete popup.
  1437. *
  1438. * @param {string=|object=} ng-model A model to bind the list of items to
  1439. * @param {string=} placeholder Placeholder text that will be forwarded to the input.
  1440. * @param {string=} secondary-placeholder Placeholder text that will be forwarded to the input,
  1441. * displayed when there is at least on item in the list
  1442. * @param {expression} md-contacts An expression expected to return contacts matching the search
  1443. * test, `$query`. If this expression involves a promise, a loading bar is displayed while
  1444. * waiting for it to resolve.
  1445. * @param {string} md-contact-name The field name of the contact object representing the
  1446. * contact's name.
  1447. * @param {string} md-contact-email The field name of the contact object representing the
  1448. * contact's email address.
  1449. * @param {string} md-contact-image The field name of the contact object representing the
  1450. * contact's image.
  1451. * @param {number=} md-min-length Specifies the minimum length of text before autocomplete will
  1452. * make suggestions
  1453. *
  1454. * @param {expression=} filter-selected Whether to filter selected contacts from the list of
  1455. * suggestions shown in the autocomplete.
  1456. *
  1457. * ***Note:** This attribute has been removed but may come back.*
  1458. *
  1459. *
  1460. *
  1461. * @usage
  1462. * <hljs lang="html">
  1463. * <md-contact-chips
  1464. * ng-model="ctrl.contacts"
  1465. * md-contacts="ctrl.querySearch($query)"
  1466. * md-contact-name="name"
  1467. * md-contact-image="image"
  1468. * md-contact-email="email"
  1469. * placeholder="To">
  1470. * </md-contact-chips>
  1471. * </hljs>
  1472. *
  1473. */
  1474. var MD_CONTACT_CHIPS_TEMPLATE = '\
  1475. <md-chips class="md-contact-chips"\
  1476. ng-model="$mdContactChipsCtrl.contacts"\
  1477. md-require-match="$mdContactChipsCtrl.requireMatch"\
  1478. md-chip-append-delay="{{$mdContactChipsCtrl.chipAppendDelay}}" \
  1479. md-autocomplete-snap>\
  1480. <md-autocomplete\
  1481. md-menu-class="md-contact-chips-suggestions"\
  1482. md-selected-item="$mdContactChipsCtrl.selectedItem"\
  1483. md-search-text="$mdContactChipsCtrl.searchText"\
  1484. md-items="item in $mdContactChipsCtrl.queryContact($mdContactChipsCtrl.searchText)"\
  1485. md-item-text="$mdContactChipsCtrl.itemName(item)"\
  1486. md-no-cache="true"\
  1487. md-min-length="$mdContactChipsCtrl.minLength"\
  1488. md-autoselect\
  1489. placeholder="{{$mdContactChipsCtrl.contacts.length == 0 ?\
  1490. $mdContactChipsCtrl.placeholder : $mdContactChipsCtrl.secondaryPlaceholder}}">\
  1491. <div class="md-contact-suggestion">\
  1492. <img \
  1493. ng-src="{{item[$mdContactChipsCtrl.contactImage]}}"\
  1494. alt="{{item[$mdContactChipsCtrl.contactName]}}"\
  1495. ng-if="item[$mdContactChipsCtrl.contactImage]" />\
  1496. <span class="md-contact-name" md-highlight-text="$mdContactChipsCtrl.searchText"\
  1497. md-highlight-flags="{{$mdContactChipsCtrl.highlightFlags}}">\
  1498. {{item[$mdContactChipsCtrl.contactName]}}\
  1499. </span>\
  1500. <span class="md-contact-email" >{{item[$mdContactChipsCtrl.contactEmail]}}</span>\
  1501. </div>\
  1502. </md-autocomplete>\
  1503. <md-chip-template>\
  1504. <div class="md-contact-avatar">\
  1505. <img \
  1506. ng-src="{{$chip[$mdContactChipsCtrl.contactImage]}}"\
  1507. alt="{{$chip[$mdContactChipsCtrl.contactName]}}"\
  1508. ng-if="$chip[$mdContactChipsCtrl.contactImage]" />\
  1509. </div>\
  1510. <div class="md-contact-name">\
  1511. {{$chip[$mdContactChipsCtrl.contactName]}}\
  1512. </div>\
  1513. </md-chip-template>\
  1514. </md-chips>';
  1515. /**
  1516. * MDContactChips Directive Definition
  1517. *
  1518. * @param $mdTheming
  1519. * @returns {*}
  1520. * ngInject
  1521. */
  1522. function MdContactChips($mdTheming, $mdUtil) {
  1523. return {
  1524. template: function(element, attrs) {
  1525. return MD_CONTACT_CHIPS_TEMPLATE;
  1526. },
  1527. restrict: 'E',
  1528. controller: 'MdContactChipsCtrl',
  1529. controllerAs: '$mdContactChipsCtrl',
  1530. bindToController: true,
  1531. compile: compile,
  1532. scope: {
  1533. contactQuery: '&mdContacts',
  1534. placeholder: '@',
  1535. secondaryPlaceholder: '@',
  1536. contactName: '@mdContactName',
  1537. contactImage: '@mdContactImage',
  1538. contactEmail: '@mdContactEmail',
  1539. contacts: '=ngModel',
  1540. requireMatch: '=?mdRequireMatch',
  1541. minLength: '=?mdMinLength',
  1542. highlightFlags: '@?mdHighlightFlags',
  1543. chipAppendDelay: '@?mdChipAppendDelay'
  1544. }
  1545. };
  1546. function compile(element, attr) {
  1547. return function postLink(scope, element, attrs, controllers) {
  1548. var contactChipsController = controllers;
  1549. $mdUtil.initOptionalProperties(scope, attr);
  1550. $mdTheming(element);
  1551. element.attr('tabindex', '-1');
  1552. attrs.$observe('mdChipAppendDelay', function(newValue) {
  1553. contactChipsController.chipAppendDelay = newValue;
  1554. });
  1555. };
  1556. }
  1557. }
  1558. })(window, window.angular);