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