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.

1550 lines
48 KiB

  1. /*!
  2. * Angular Material Design
  3. * https://github.com/angular/material
  4. * @license MIT
  5. * v1.1.1
  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"];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) {
  214. var hintTemplate = $mdUtil.processTemplate(DELETE_HINT_TEMPLATE);
  215. return {
  216. restrict: 'E',
  217. require: ['^?mdChips', 'mdChip'],
  218. compile: compile,
  219. controller: 'MdChipCtrl'
  220. };
  221. function compile(element, attr) {
  222. // Append the delete template
  223. element.append($mdUtil.processTemplate(hintTemplate));
  224. return function postLink(scope, element, attr, ctrls) {
  225. var chipsController = ctrls.shift();
  226. var chipController = ctrls.shift();
  227. $mdTheming(element);
  228. if (chipsController) {
  229. chipController.init(chipsController);
  230. angular
  231. .element(element[0]
  232. .querySelector('.md-chip-content'))
  233. .on('blur', function () {
  234. chipsController.resetSelectedChip();
  235. chipsController.$scope.$applyAsync();
  236. });
  237. }
  238. };
  239. }
  240. }
  241. MdChipRemove.$inject = ["$timeout"];angular
  242. .module('material.components.chips')
  243. .directive('mdChipRemove', MdChipRemove);
  244. /**
  245. * @ngdoc directive
  246. * @name mdChipRemove
  247. * @restrict A
  248. * @module material.components.chips
  249. *
  250. * @description
  251. * Designates an element to be used as the delete button for a chip. <br/>
  252. * This element is passed as a child of the `md-chips` element.
  253. *
  254. * The designated button will be just appended to the chip and removes the given chip on click.<br/>
  255. * By default the button is not being styled by the `md-chips` component.
  256. *
  257. * @usage
  258. * <hljs lang="html">
  259. * <md-chips>
  260. * <button md-chip-remove="">
  261. * <md-icon md-svg-icon="md-close"></md-icon>
  262. * </button>
  263. * </md-chips>
  264. * </hljs>
  265. */
  266. /**
  267. * MdChipRemove Directive Definition.
  268. *
  269. * @param $timeout
  270. * @returns {{restrict: string, require: string[], link: Function, scope: boolean}}
  271. * @constructor
  272. */
  273. function MdChipRemove ($timeout) {
  274. return {
  275. restrict: 'A',
  276. require: '^mdChips',
  277. scope: false,
  278. link: postLink
  279. };
  280. function postLink(scope, element, attr, ctrl) {
  281. element.on('click', function(event) {
  282. scope.$apply(function() {
  283. ctrl.removeChip(scope.$$replacedScope.$index);
  284. });
  285. });
  286. // Child elements aren't available until after a $timeout tick as they are hidden by an
  287. // `ng-if`. see http://goo.gl/zIWfuw
  288. $timeout(function() {
  289. element.attr({ tabindex: -1, 'aria-hidden': true });
  290. element.find('button').attr('tabindex', '-1');
  291. });
  292. }
  293. }
  294. MdChipTransclude.$inject = ["$compile"];angular
  295. .module('material.components.chips')
  296. .directive('mdChipTransclude', MdChipTransclude);
  297. function MdChipTransclude ($compile) {
  298. return {
  299. restrict: 'EA',
  300. terminal: true,
  301. link: link,
  302. scope: false
  303. };
  304. function link (scope, element, attr) {
  305. var ctrl = scope.$parent.$mdChipsCtrl,
  306. newScope = ctrl.parent.$new(false, ctrl.parent);
  307. newScope.$$replacedScope = scope;
  308. newScope.$chip = scope.$chip;
  309. newScope.$index = scope.$index;
  310. newScope.$mdChipsCtrl = ctrl;
  311. var newHtml = ctrl.$scope.$eval(attr.mdChipTransclude);
  312. element.html(newHtml);
  313. $compile(element.contents())(newScope);
  314. }
  315. }
  316. MdChipsCtrl.$inject = ["$scope", "$attrs", "$mdConstant", "$log", "$element", "$timeout", "$mdUtil"];angular
  317. .module('material.components.chips')
  318. .controller('MdChipsCtrl', MdChipsCtrl);
  319. /**
  320. * Controller for the MdChips component. Responsible for adding to and
  321. * removing from the list of chips, marking chips as selected, and binding to
  322. * the models of various input components.
  323. *
  324. * @param $scope
  325. * @param $attrs
  326. * @param $mdConstant
  327. * @param $log
  328. * @param $element
  329. * @param $timeout
  330. * @param $mdUtil
  331. * @constructor
  332. */
  333. function MdChipsCtrl ($scope, $attrs, $mdConstant, $log, $element, $timeout, $mdUtil) {
  334. /** @type {$timeout} **/
  335. this.$timeout = $timeout;
  336. /** @type {Object} */
  337. this.$mdConstant = $mdConstant;
  338. /** @type {angular.$scope} */
  339. this.$scope = $scope;
  340. /** @type {angular.$scope} */
  341. this.parent = $scope.$parent;
  342. /** @type {$log} */
  343. this.$log = $log;
  344. /** @type {$element} */
  345. this.$element = $element;
  346. /** @type {angular.NgModelController} */
  347. this.ngModelCtrl = null;
  348. /** @type {angular.NgModelController} */
  349. this.userInputNgModelCtrl = null;
  350. /** @type {MdAutocompleteCtrl} */
  351. this.autocompleteCtrl = null;
  352. /** @type {Element} */
  353. this.userInputElement = null;
  354. /** @type {Array.<Object>} */
  355. this.items = [];
  356. /** @type {number} */
  357. this.selectedChip = -1;
  358. /** @type {string} */
  359. this.enableChipEdit = $mdUtil.parseAttributeBoolean($attrs.mdEnableChipEdit);
  360. /** @type {string} */
  361. this.addOnBlur = $mdUtil.parseAttributeBoolean($attrs.mdAddOnBlur);
  362. /**
  363. * Hidden hint text for how to delete a chip. Used to give context to screen readers.
  364. * @type {string}
  365. */
  366. this.deleteHint = 'Press delete to remove this chip.';
  367. /**
  368. * Hidden label for the delete button. Used to give context to screen readers.
  369. * @type {string}
  370. */
  371. this.deleteButtonLabel = 'Remove';
  372. /**
  373. * Model used by the input element.
  374. * @type {string}
  375. */
  376. this.chipBuffer = '';
  377. /**
  378. * Whether to use the transformChip expression to transform the chip buffer
  379. * before appending it to the list.
  380. * @type {boolean}
  381. */
  382. this.useTransformChip = false;
  383. /**
  384. * Whether to use the onAdd expression to notify of chip additions.
  385. * @type {boolean}
  386. */
  387. this.useOnAdd = false;
  388. /**
  389. * Whether to use the onRemove expression to notify of chip removals.
  390. * @type {boolean}
  391. */
  392. this.useOnRemove = false;
  393. /**
  394. * Whether to use the onSelect expression to notify the component's user
  395. * after selecting a chip from the list.
  396. * @type {boolean}
  397. */
  398. }
  399. /**
  400. * Handles the keydown event on the input element: by default <enter> appends
  401. * the buffer to the chip list, while backspace removes the last chip in the
  402. * list if the current buffer is empty.
  403. * @param event
  404. */
  405. MdChipsCtrl.prototype.inputKeydown = function(event) {
  406. var chipBuffer = this.getChipBuffer();
  407. // If we have an autocomplete, and it handled the event, we have nothing to do
  408. if (this.autocompleteCtrl && event.isDefaultPrevented && event.isDefaultPrevented()) {
  409. return;
  410. }
  411. if (event.keyCode === this.$mdConstant.KEY_CODE.BACKSPACE) {
  412. // Only select and focus the previous chip, if the current caret position of the
  413. // input element is at the beginning.
  414. if (this.getCursorPosition(event.target) !== 0) {
  415. return;
  416. }
  417. event.preventDefault();
  418. event.stopPropagation();
  419. if (this.items.length) {
  420. this.selectAndFocusChipSafe(this.items.length - 1);
  421. }
  422. return;
  423. }
  424. // By default <enter> appends the buffer to the chip list.
  425. if (!this.separatorKeys || this.separatorKeys.length < 1) {
  426. this.separatorKeys = [this.$mdConstant.KEY_CODE.ENTER];
  427. }
  428. // Support additional separator key codes in an array of `md-separator-keys`.
  429. if (this.separatorKeys.indexOf(event.keyCode) !== -1) {
  430. if ((this.autocompleteCtrl && this.requireMatch) || !chipBuffer) return;
  431. event.preventDefault();
  432. // Only append the chip and reset the chip buffer if the max chips limit isn't reached.
  433. if (this.hasMaxChipsReached()) return;
  434. this.appendChip(chipBuffer.trim());
  435. this.resetChipBuffer();
  436. }
  437. };
  438. /**
  439. * Returns the cursor position of the specified input element.
  440. * @param element HTMLInputElement
  441. * @returns {Number} Cursor Position of the input.
  442. */
  443. MdChipsCtrl.prototype.getCursorPosition = function(element) {
  444. /*
  445. * Figure out whether the current input for the chips buffer is valid for using
  446. * the selectionStart / end property to retrieve the cursor position.
  447. * Some browsers do not allow the use of those attributes, on different input types.
  448. */
  449. try {
  450. if (element.selectionStart === element.selectionEnd) {
  451. return element.selectionStart;
  452. }
  453. } catch (e) {
  454. if (!element.value) {
  455. return 0;
  456. }
  457. }
  458. };
  459. /**
  460. * Updates the content of the chip at given index
  461. * @param chipIndex
  462. * @param chipContents
  463. */
  464. MdChipsCtrl.prototype.updateChipContents = function(chipIndex, chipContents){
  465. if(chipIndex >= 0 && chipIndex < this.items.length) {
  466. this.items[chipIndex] = chipContents;
  467. this.ngModelCtrl.$setDirty();
  468. }
  469. };
  470. /**
  471. * Returns true if a chip is currently being edited. False otherwise.
  472. * @return {boolean}
  473. */
  474. MdChipsCtrl.prototype.isEditingChip = function() {
  475. return !!this.$element[0].getElementsByClassName('_md-chip-editing').length;
  476. };
  477. MdChipsCtrl.prototype.isRemovable = function() {
  478. // Return false if we have static chips
  479. if (!this.ngModelCtrl) {
  480. return false;
  481. }
  482. return this.readonly ? this.removable :
  483. angular.isDefined(this.removable) ? this.removable : true;
  484. };
  485. /**
  486. * Handles the keydown event on the chip elements: backspace removes the selected chip, arrow
  487. * keys switch which chips is active
  488. * @param event
  489. */
  490. MdChipsCtrl.prototype.chipKeydown = function (event) {
  491. if (this.getChipBuffer()) return;
  492. if (this.isEditingChip()) return;
  493. switch (event.keyCode) {
  494. case this.$mdConstant.KEY_CODE.BACKSPACE:
  495. case this.$mdConstant.KEY_CODE.DELETE:
  496. if (this.selectedChip < 0) return;
  497. event.preventDefault();
  498. // Cancel the delete action only after the event cancel. Otherwise the page will go back.
  499. if (!this.isRemovable()) return;
  500. this.removeAndSelectAdjacentChip(this.selectedChip);
  501. break;
  502. case this.$mdConstant.KEY_CODE.LEFT_ARROW:
  503. event.preventDefault();
  504. if (this.selectedChip < 0) this.selectedChip = this.items.length;
  505. if (this.items.length) this.selectAndFocusChipSafe(this.selectedChip - 1);
  506. break;
  507. case this.$mdConstant.KEY_CODE.RIGHT_ARROW:
  508. event.preventDefault();
  509. this.selectAndFocusChipSafe(this.selectedChip + 1);
  510. break;
  511. case this.$mdConstant.KEY_CODE.ESCAPE:
  512. case this.$mdConstant.KEY_CODE.TAB:
  513. if (this.selectedChip < 0) return;
  514. event.preventDefault();
  515. this.onFocus();
  516. break;
  517. }
  518. };
  519. /**
  520. * Get the input's placeholder - uses `placeholder` when list is empty and `secondary-placeholder`
  521. * when the list is non-empty. If `secondary-placeholder` is not provided, `placeholder` is used
  522. * always.
  523. */
  524. MdChipsCtrl.prototype.getPlaceholder = function() {
  525. // Allow `secondary-placeholder` to be blank.
  526. var useSecondary = (this.items && this.items.length &&
  527. (this.secondaryPlaceholder == '' || this.secondaryPlaceholder));
  528. return useSecondary ? this.secondaryPlaceholder : this.placeholder;
  529. };
  530. /**
  531. * Removes chip at {@code index} and selects the adjacent chip.
  532. * @param index
  533. */
  534. MdChipsCtrl.prototype.removeAndSelectAdjacentChip = function(index) {
  535. var selIndex = this.getAdjacentChipIndex(index);
  536. this.removeChip(index);
  537. this.$timeout(angular.bind(this, function () {
  538. this.selectAndFocusChipSafe(selIndex);
  539. }));
  540. };
  541. /**
  542. * Sets the selected chip index to -1.
  543. */
  544. MdChipsCtrl.prototype.resetSelectedChip = function() {
  545. this.selectedChip = -1;
  546. };
  547. /**
  548. * Gets the index of an adjacent chip to select after deletion. Adjacency is
  549. * determined as the next chip in the list, unless the target chip is the
  550. * last in the list, then it is the chip immediately preceding the target. If
  551. * there is only one item in the list, -1 is returned (select none).
  552. * The number returned is the index to select AFTER the target has been
  553. * removed.
  554. * If the current chip is not selected, then -1 is returned to select none.
  555. */
  556. MdChipsCtrl.prototype.getAdjacentChipIndex = function(index) {
  557. var len = this.items.length - 1;
  558. return (len == 0) ? -1 :
  559. (index == len) ? index -1 : index;
  560. };
  561. /**
  562. * Append the contents of the buffer to the chip list. This method will first
  563. * call out to the md-transform-chip method, if provided.
  564. *
  565. * @param newChip
  566. */
  567. MdChipsCtrl.prototype.appendChip = function(newChip) {
  568. if (this.useTransformChip && this.transformChip) {
  569. var transformedChip = this.transformChip({'$chip': newChip});
  570. // Check to make sure the chip is defined before assigning it, otherwise, we'll just assume
  571. // they want the string version.
  572. if (angular.isDefined(transformedChip)) {
  573. newChip = transformedChip;
  574. }
  575. }
  576. // If items contains an identical object to newChip, do not append
  577. if (angular.isObject(newChip)){
  578. var identical = this.items.some(function(item){
  579. return angular.equals(newChip, item);
  580. });
  581. if (identical) return;
  582. }
  583. // Check for a null (but not undefined), or existing chip and cancel appending
  584. if (newChip == null || this.items.indexOf(newChip) + 1) return;
  585. // Append the new chip onto our list
  586. var index = this.items.push(newChip);
  587. // Update model validation
  588. this.ngModelCtrl.$setDirty();
  589. this.validateModel();
  590. // If they provide the md-on-add attribute, notify them of the chip addition
  591. if (this.useOnAdd && this.onAdd) {
  592. this.onAdd({ '$chip': newChip, '$index': index });
  593. }
  594. };
  595. /**
  596. * Sets whether to use the md-transform-chip expression. This expression is
  597. * bound to scope and controller in {@code MdChipsDirective} as
  598. * {@code transformChip}. Due to the nature of directive scope bindings, the
  599. * controller cannot know on its own/from the scope whether an expression was
  600. * actually provided.
  601. */
  602. MdChipsCtrl.prototype.useTransformChipExpression = function() {
  603. this.useTransformChip = true;
  604. };
  605. /**
  606. * Sets whether to use the md-on-add expression. This expression is
  607. * bound to scope and controller in {@code MdChipsDirective} as
  608. * {@code onAdd}. Due to the nature of directive scope bindings, the
  609. * controller cannot know on its own/from the scope whether an expression was
  610. * actually provided.
  611. */
  612. MdChipsCtrl.prototype.useOnAddExpression = function() {
  613. this.useOnAdd = true;
  614. };
  615. /**
  616. * Sets whether to use the md-on-remove expression. This expression is
  617. * bound to scope and controller in {@code MdChipsDirective} as
  618. * {@code onRemove}. Due to the nature of directive scope bindings, the
  619. * controller cannot know on its own/from the scope whether an expression was
  620. * actually provided.
  621. */
  622. MdChipsCtrl.prototype.useOnRemoveExpression = function() {
  623. this.useOnRemove = true;
  624. };
  625. /*
  626. * Sets whether to use the md-on-select expression. This expression is
  627. * bound to scope and controller in {@code MdChipsDirective} as
  628. * {@code onSelect}. Due to the nature of directive scope bindings, the
  629. * controller cannot know on its own/from the scope whether an expression was
  630. * actually provided.
  631. */
  632. MdChipsCtrl.prototype.useOnSelectExpression = function() {
  633. this.useOnSelect = true;
  634. };
  635. /**
  636. * Gets the input buffer. The input buffer can be the model bound to the
  637. * default input item {@code this.chipBuffer}, the {@code selectedItem}
  638. * model of an {@code md-autocomplete}, or, through some magic, the model
  639. * bound to any inpput or text area element found within a
  640. * {@code md-input-container} element.
  641. * @return {Object|string}
  642. */
  643. MdChipsCtrl.prototype.getChipBuffer = function() {
  644. return !this.userInputElement ? this.chipBuffer :
  645. this.userInputNgModelCtrl ? this.userInputNgModelCtrl.$viewValue :
  646. this.userInputElement[0].value;
  647. };
  648. /**
  649. * Resets the input buffer for either the internal input or user provided input element.
  650. */
  651. MdChipsCtrl.prototype.resetChipBuffer = function() {
  652. if (this.userInputElement) {
  653. if (this.userInputNgModelCtrl) {
  654. this.userInputNgModelCtrl.$setViewValue('');
  655. this.userInputNgModelCtrl.$render();
  656. } else {
  657. this.userInputElement[0].value = '';
  658. }
  659. } else {
  660. this.chipBuffer = '';
  661. }
  662. };
  663. MdChipsCtrl.prototype.hasMaxChipsReached = function() {
  664. if (angular.isString(this.maxChips)) this.maxChips = parseInt(this.maxChips, 10) || 0;
  665. return this.maxChips > 0 && this.items.length >= this.maxChips;
  666. };
  667. /**
  668. * Updates the validity properties for the ngModel.
  669. */
  670. MdChipsCtrl.prototype.validateModel = function() {
  671. this.ngModelCtrl.$setValidity('md-max-chips', !this.hasMaxChipsReached());
  672. };
  673. /**
  674. * Removes the chip at the given index.
  675. * @param index
  676. */
  677. MdChipsCtrl.prototype.removeChip = function(index) {
  678. var removed = this.items.splice(index, 1);
  679. // Update model validation
  680. this.ngModelCtrl.$setDirty();
  681. this.validateModel();
  682. if (removed && removed.length && this.useOnRemove && this.onRemove) {
  683. this.onRemove({ '$chip': removed[0], '$index': index });
  684. }
  685. };
  686. MdChipsCtrl.prototype.removeChipAndFocusInput = function (index) {
  687. this.removeChip(index);
  688. if (this.autocompleteCtrl) {
  689. // Always hide the autocomplete dropdown before focusing the autocomplete input.
  690. // Wait for the input to move horizontally, because the chip was removed.
  691. // This can lead to an incorrect dropdown position.
  692. this.autocompleteCtrl.hidden = true;
  693. this.$mdUtil.nextTick(this.onFocus.bind(this));
  694. } else {
  695. this.onFocus();
  696. }
  697. };
  698. /**
  699. * Selects the chip at `index`,
  700. * @param index
  701. */
  702. MdChipsCtrl.prototype.selectAndFocusChipSafe = function(index) {
  703. if (!this.items.length) {
  704. this.selectChip(-1);
  705. this.onFocus();
  706. return;
  707. }
  708. if (index === this.items.length) return this.onFocus();
  709. index = Math.max(index, 0);
  710. index = Math.min(index, this.items.length - 1);
  711. this.selectChip(index);
  712. this.focusChip(index);
  713. };
  714. /**
  715. * Marks the chip at the given index as selected.
  716. * @param index
  717. */
  718. MdChipsCtrl.prototype.selectChip = function(index) {
  719. if (index >= -1 && index <= this.items.length) {
  720. this.selectedChip = index;
  721. // Fire the onSelect if provided
  722. if (this.useOnSelect && this.onSelect) {
  723. this.onSelect({'$chip': this.items[this.selectedChip] });
  724. }
  725. } else {
  726. this.$log.warn('Selected Chip index out of bounds; ignoring.');
  727. }
  728. };
  729. /**
  730. * Selects the chip at `index` and gives it focus.
  731. * @param index
  732. */
  733. MdChipsCtrl.prototype.selectAndFocusChip = function(index) {
  734. this.selectChip(index);
  735. if (index != -1) {
  736. this.focusChip(index);
  737. }
  738. };
  739. /**
  740. * Call `focus()` on the chip at `index`
  741. */
  742. MdChipsCtrl.prototype.focusChip = function(index) {
  743. this.$element[0].querySelector('md-chip[index="' + index + '"] .md-chip-content').focus();
  744. };
  745. /**
  746. * Configures the required interactions with the ngModel Controller.
  747. * Specifically, set {@code this.items} to the {@code NgModelCtrl#$viewVale}.
  748. * @param ngModelCtrl
  749. */
  750. MdChipsCtrl.prototype.configureNgModel = function(ngModelCtrl) {
  751. this.ngModelCtrl = ngModelCtrl;
  752. var self = this;
  753. ngModelCtrl.$render = function() {
  754. // model is updated. do something.
  755. self.items = self.ngModelCtrl.$viewValue;
  756. };
  757. };
  758. MdChipsCtrl.prototype.onFocus = function () {
  759. var input = this.$element[0].querySelector('input');
  760. input && input.focus();
  761. this.resetSelectedChip();
  762. };
  763. MdChipsCtrl.prototype.onInputFocus = function () {
  764. this.inputHasFocus = true;
  765. this.resetSelectedChip();
  766. };
  767. MdChipsCtrl.prototype.onInputBlur = function () {
  768. this.inputHasFocus = false;
  769. var chipBuffer = this.getChipBuffer().trim();
  770. // Update the custom chip validators.
  771. this.validateModel();
  772. var isModelValid = this.ngModelCtrl.$valid;
  773. if (this.userInputNgModelCtrl) {
  774. isModelValid &= this.userInputNgModelCtrl.$valid;
  775. }
  776. // Only append the chip and reset the chip buffer if the chips and input ngModel is valid.
  777. if (this.addOnBlur && chipBuffer && isModelValid) {
  778. this.appendChip(chipBuffer);
  779. this.resetChipBuffer();
  780. }
  781. };
  782. /**
  783. * Configure event bindings on a user-provided input element.
  784. * @param inputElement
  785. */
  786. MdChipsCtrl.prototype.configureUserInput = function(inputElement) {
  787. this.userInputElement = inputElement;
  788. // Find the NgModelCtrl for the input element
  789. var ngModelCtrl = inputElement.controller('ngModel');
  790. // `.controller` will look in the parent as well.
  791. if (ngModelCtrl != this.ngModelCtrl) {
  792. this.userInputNgModelCtrl = ngModelCtrl;
  793. }
  794. var scope = this.$scope;
  795. var ctrl = this;
  796. // Run all of the events using evalAsync because a focus may fire a blur in the same digest loop
  797. var scopeApplyFn = function(event, fn) {
  798. scope.$evalAsync(angular.bind(ctrl, fn, event));
  799. };
  800. // Bind to keydown and focus events of input
  801. inputElement
  802. .attr({ tabindex: 0 })
  803. .on('keydown', function(event) { scopeApplyFn(event, ctrl.inputKeydown) })
  804. .on('focus', function(event) { scopeApplyFn(event, ctrl.onInputFocus) })
  805. .on('blur', function(event) { scopeApplyFn(event, ctrl.onInputBlur) })
  806. };
  807. MdChipsCtrl.prototype.configureAutocomplete = function(ctrl) {
  808. if (ctrl) {
  809. this.autocompleteCtrl = ctrl;
  810. ctrl.registerSelectedItemWatcher(angular.bind(this, function (item) {
  811. if (item) {
  812. // Only append the chip and reset the chip buffer if the max chips limit isn't reached.
  813. if (this.hasMaxChipsReached()) return;
  814. this.appendChip(item);
  815. this.resetChipBuffer();
  816. }
  817. }));
  818. this.$element.find('input')
  819. .on('focus',angular.bind(this, this.onInputFocus) )
  820. .on('blur', angular.bind(this, this.onInputBlur) );
  821. }
  822. };
  823. MdChipsCtrl.prototype.hasFocus = function () {
  824. return this.inputHasFocus || this.selectedChip >= 0;
  825. };
  826. MdChips.$inject = ["$mdTheming", "$mdUtil", "$compile", "$log", "$timeout", "$$mdSvgRegistry"];angular
  827. .module('material.components.chips')
  828. .directive('mdChips', MdChips);
  829. /**
  830. * @ngdoc directive
  831. * @name mdChips
  832. * @module material.components.chips
  833. *
  834. * @description
  835. * `<md-chips>` is an input component for building lists of strings or objects. The list items are
  836. * displayed as 'chips'. This component can make use of an `<input>` element or an
  837. * `<md-autocomplete>` element.
  838. *
  839. * ### Custom templates
  840. * A custom template may be provided to render the content of each chip. This is achieved by
  841. * specifying an `<md-chip-template>` element containing the custom content as a child of
  842. * `<md-chips>`.
  843. *
  844. * Note: Any attributes on
  845. * `<md-chip-template>` will be dropped as only the innerHTML is used for the chip template. The
  846. * variables `$chip` and `$index` are available in the scope of `<md-chip-template>`, representing
  847. * the chip object and its index in the list of chips, respectively.
  848. * To override the chip delete control, include an element (ideally a button) with the attribute
  849. * `md-chip-remove`. A click listener to remove the chip will be added automatically. The element
  850. * is also placed as a sibling to the chip content (on which there are also click listeners) to
  851. * avoid a nested ng-click situation.
  852. *
  853. * <h3> Pending Features </h3>
  854. * <ul style="padding-left:20px;">
  855. *
  856. * <ul>Style
  857. * <li>Colours for hover, press states (ripple?).</li>
  858. * </ul>
  859. *
  860. * <ul>Validation
  861. * <li>allow a validation callback</li>
  862. * <li>hilighting style for invalid chips</li>
  863. * </ul>
  864. *
  865. * <ul>Item mutation
  866. * <li>Support `
  867. * <md-chip-edit>` template, show/hide the edit element on tap/click? double tap/double
  868. * click?
  869. * </li>
  870. * </ul>
  871. *
  872. * <ul>Truncation and Disambiguation (?)
  873. * <li>Truncate chip text where possible, but do not truncate entries such that two are
  874. * indistinguishable.</li>
  875. * </ul>
  876. *
  877. * <ul>Drag and Drop
  878. * <li>Drag and drop chips between related `<md-chips>` elements.
  879. * </li>
  880. * </ul>
  881. * </ul>
  882. *
  883. * <span style="font-size:.8em;text-align:center">
  884. * Warning: This component is a WORK IN PROGRESS. If you use it now,
  885. * it will probably break on you in the future.
  886. * </span>
  887. *
  888. * Sometimes developers want to limit the amount of possible chips.<br/>
  889. * You can specify the maximum amount of chips by using the following markup.
  890. *
  891. * <hljs lang="html">
  892. * <md-chips
  893. * ng-model="myItems"
  894. * placeholder="Add an item"
  895. * md-max-chips="5">
  896. * </md-chips>
  897. * </hljs>
  898. *
  899. * In some cases, you have an autocomplete inside of the `md-chips`.<br/>
  900. * When the maximum amount of chips has been reached, you can also disable the autocomplete selection.<br/>
  901. * Here is an example markup.
  902. *
  903. * <hljs lang="html">
  904. * <md-chips ng-model="myItems" md-max-chips="5">
  905. * <md-autocomplete ng-hide="myItems.length > 5" ...></md-autocomplete>
  906. * </md-chips>
  907. * </hljs>
  908. *
  909. * @param {string=|object=} ng-model A model to bind the list of items to
  910. * @param {string=} placeholder Placeholder text that will be forwarded to the input.
  911. * @param {string=} secondary-placeholder Placeholder text that will be forwarded to the input,
  912. * displayed when there is at least one item in the list
  913. * @param {boolean=} md-removable Enables or disables the deletion of chips through the
  914. * removal icon or the Delete/Backspace key. Defaults to true.
  915. * @param {boolean=} readonly Disables list manipulation (deleting or adding list items), hiding
  916. * the input and delete buttons. If no `ng-model` is provided, the chips will automatically be
  917. * marked as readonly.<br/><br/>
  918. * When `md-removable` is not defined, the `md-remove` behavior will be overwritten and disabled.
  919. * @param {string=} md-enable-chip-edit Set this to "true" to enable editing of chip contents. The user can
  920. * go into edit mode with pressing "space", "enter", or double clicking on the chip. Chip edit is only
  921. * supported for chips with basic template.
  922. * @param {number=} md-max-chips The maximum number of chips allowed to add through user input.
  923. * <br/><br/>The validation property `md-max-chips` can be used when the max chips
  924. * amount is reached.
  925. * @param {boolean=} md-add-on-blur When set to true, remaining text inside of the input will
  926. * be converted into a new chip on blur.
  927. * @param {expression} md-transform-chip An expression of form `myFunction($chip)` that when called
  928. * expects one of the following return values:
  929. * - an object representing the `$chip` input string
  930. * - `undefined` to simply add the `$chip` input string, or
  931. * - `null` to prevent the chip from being appended
  932. * @param {expression=} md-on-add An expression which will be called when a chip has been
  933. * added.
  934. * @param {expression=} md-on-remove An expression which will be called when a chip has been
  935. * removed.
  936. * @param {expression=} md-on-select An expression which will be called when a chip is selected.
  937. * @param {boolean} md-require-match If true, and the chips template contains an autocomplete,
  938. * only allow selection of pre-defined chips (i.e. you cannot add new ones).
  939. * @param {string=} delete-hint A string read by screen readers instructing users that pressing
  940. * the delete key will remove the chip.
  941. * @param {string=} delete-button-label A label for the delete button. Also hidden and read by
  942. * screen readers.
  943. * @param {expression=} md-separator-keys An array of key codes used to separate chips.
  944. *
  945. * @usage
  946. * <hljs lang="html">
  947. * <md-chips
  948. * ng-model="myItems"
  949. * placeholder="Add an item"
  950. * readonly="isReadOnly">
  951. * </md-chips>
  952. * </hljs>
  953. *
  954. * <h3>Validation</h3>
  955. * When using [ngMessages](https://docs.angularjs.org/api/ngMessages), you can show errors based
  956. * on our custom validators.
  957. * <hljs lang="html">
  958. * <form name="userForm">
  959. * <md-chips
  960. * name="fruits"
  961. * ng-model="myItems"
  962. * placeholder="Add an item"
  963. * md-max-chips="5">
  964. * </md-chips>
  965. * <div ng-messages="userForm.fruits.$error" ng-if="userForm.$dirty">
  966. * <div ng-message="md-max-chips">You reached the maximum amount of chips</div>
  967. * </div>
  968. * </form>
  969. * </hljs>
  970. *
  971. */
  972. var MD_CHIPS_TEMPLATE = '\
  973. <md-chips-wrap\
  974. ng-keydown="$mdChipsCtrl.chipKeydown($event)"\
  975. ng-class="{ \'md-focused\': $mdChipsCtrl.hasFocus(), \
  976. \'md-readonly\': !$mdChipsCtrl.ngModelCtrl || $mdChipsCtrl.readonly,\
  977. \'md-removable\': $mdChipsCtrl.isRemovable() }"\
  978. class="md-chips">\
  979. <md-chip ng-repeat="$chip in $mdChipsCtrl.items"\
  980. index="{{$index}}"\
  981. ng-class="{\'md-focused\': $mdChipsCtrl.selectedChip == $index, \'md-readonly\': !$mdChipsCtrl.ngModelCtrl || $mdChipsCtrl.readonly}">\
  982. <div class="md-chip-content"\
  983. tabindex="-1"\
  984. aria-hidden="true"\
  985. ng-click="!$mdChipsCtrl.readonly && $mdChipsCtrl.focusChip($index)"\
  986. ng-focus="!$mdChipsCtrl.readonly && $mdChipsCtrl.selectChip($index)"\
  987. md-chip-transclude="$mdChipsCtrl.chipContentsTemplate"></div>\
  988. <div ng-if="$mdChipsCtrl.isRemovable()"\
  989. class="md-chip-remove-container"\
  990. md-chip-transclude="$mdChipsCtrl.chipRemoveTemplate"></div>\
  991. </md-chip>\
  992. <div class="md-chip-input-container" ng-if="!$mdChipsCtrl.readonly && $mdChipsCtrl.ngModelCtrl">\
  993. <div md-chip-transclude="$mdChipsCtrl.chipInputTemplate"></div>\
  994. </div>\
  995. </md-chips-wrap>';
  996. var CHIP_INPUT_TEMPLATE = '\
  997. <input\
  998. class="md-input"\
  999. tabindex="0"\
  1000. placeholder="{{$mdChipsCtrl.getPlaceholder()}}"\
  1001. aria-label="{{$mdChipsCtrl.getPlaceholder()}}"\
  1002. ng-model="$mdChipsCtrl.chipBuffer"\
  1003. ng-focus="$mdChipsCtrl.onInputFocus()"\
  1004. ng-blur="$mdChipsCtrl.onInputBlur()"\
  1005. ng-keydown="$mdChipsCtrl.inputKeydown($event)">';
  1006. var CHIP_DEFAULT_TEMPLATE = '\
  1007. <span>{{$chip}}</span>';
  1008. var CHIP_REMOVE_TEMPLATE = '\
  1009. <button\
  1010. class="md-chip-remove"\
  1011. ng-if="$mdChipsCtrl.isRemovable()"\
  1012. ng-click="$mdChipsCtrl.removeChipAndFocusInput($$replacedScope.$index)"\
  1013. type="button"\
  1014. aria-hidden="true"\
  1015. tabindex="-1">\
  1016. <md-icon md-svg-src="{{ $mdChipsCtrl.mdCloseIcon }}"></md-icon>\
  1017. <span class="md-visually-hidden">\
  1018. {{$mdChipsCtrl.deleteButtonLabel}}\
  1019. </span>\
  1020. </button>';
  1021. /**
  1022. * MDChips Directive Definition
  1023. */
  1024. function MdChips ($mdTheming, $mdUtil, $compile, $log, $timeout, $$mdSvgRegistry) {
  1025. // Run our templates through $mdUtil.processTemplate() to allow custom start/end symbols
  1026. var templates = getTemplates();
  1027. return {
  1028. template: function(element, attrs) {
  1029. // Clone the element into an attribute. By prepending the attribute
  1030. // name with '$', Angular won't write it into the DOM. The cloned
  1031. // element propagates to the link function via the attrs argument,
  1032. // where various contained-elements can be consumed.
  1033. attrs['$mdUserTemplate'] = element.clone();
  1034. return templates.chips;
  1035. },
  1036. require: ['mdChips'],
  1037. restrict: 'E',
  1038. controller: 'MdChipsCtrl',
  1039. controllerAs: '$mdChipsCtrl',
  1040. bindToController: true,
  1041. compile: compile,
  1042. scope: {
  1043. readonly: '=readonly',
  1044. removable: '=mdRemovable',
  1045. placeholder: '@',
  1046. secondaryPlaceholder: '@',
  1047. maxChips: '@mdMaxChips',
  1048. transformChip: '&mdTransformChip',
  1049. onAppend: '&mdOnAppend',
  1050. onAdd: '&mdOnAdd',
  1051. onRemove: '&mdOnRemove',
  1052. onSelect: '&mdOnSelect',
  1053. deleteHint: '@',
  1054. deleteButtonLabel: '@',
  1055. separatorKeys: '=?mdSeparatorKeys',
  1056. requireMatch: '=?mdRequireMatch'
  1057. }
  1058. };
  1059. /**
  1060. * Builds the final template for `md-chips` and returns the postLink function.
  1061. *
  1062. * Building the template involves 3 key components:
  1063. * static chips
  1064. * chip template
  1065. * input control
  1066. *
  1067. * If no `ng-model` is provided, only the static chip work needs to be done.
  1068. *
  1069. * If no user-passed `md-chip-template` exists, the default template is used. This resulting
  1070. * template is appended to the chip content element.
  1071. *
  1072. * The remove button may be overridden by passing an element with an md-chip-remove attribute.
  1073. *
  1074. * If an `input` or `md-autocomplete` element is provided by the caller, it is set aside for
  1075. * transclusion later. The transclusion happens in `postLink` as the parent scope is required.
  1076. * If no user input is provided, a default one is appended to the input container node in the
  1077. * template.
  1078. *
  1079. * Static Chips (i.e. `md-chip` elements passed from the caller) are gathered and set aside for
  1080. * transclusion in the `postLink` function.
  1081. *
  1082. *
  1083. * @param element
  1084. * @param attr
  1085. * @returns {Function}
  1086. */
  1087. function compile(element, attr) {
  1088. // Grab the user template from attr and reset the attribute to null.
  1089. var userTemplate = attr['$mdUserTemplate'];
  1090. attr['$mdUserTemplate'] = null;
  1091. var chipTemplate = getTemplateByQuery('md-chips>md-chip-template');
  1092. var chipRemoveSelector = $mdUtil
  1093. .prefixer()
  1094. .buildList('md-chip-remove')
  1095. .map(function(attr) {
  1096. return 'md-chips>*[' + attr + ']';
  1097. })
  1098. .join(',');
  1099. // Set the chip remove, chip contents and chip input templates. The link function will put
  1100. // them on the scope for transclusion later.
  1101. var chipRemoveTemplate = getTemplateByQuery(chipRemoveSelector) || templates.remove,
  1102. chipContentsTemplate = chipTemplate || templates.default,
  1103. chipInputTemplate = getTemplateByQuery('md-chips>md-autocomplete')
  1104. || getTemplateByQuery('md-chips>input')
  1105. || templates.input,
  1106. staticChips = userTemplate.find('md-chip');
  1107. // Warn of malformed template. See #2545
  1108. if (userTemplate[0].querySelector('md-chip-template>*[md-chip-remove]')) {
  1109. $log.warn('invalid placement of md-chip-remove within md-chip-template.');
  1110. }
  1111. function getTemplateByQuery (query) {
  1112. if (!attr.ngModel) return;
  1113. var element = userTemplate[0].querySelector(query);
  1114. return element && element.outerHTML;
  1115. }
  1116. /**
  1117. * Configures controller and transcludes.
  1118. */
  1119. return function postLink(scope, element, attrs, controllers) {
  1120. $mdUtil.initOptionalProperties(scope, attr);
  1121. $mdTheming(element);
  1122. var mdChipsCtrl = controllers[0];
  1123. if(chipTemplate) {
  1124. // Chip editing functionality assumes we are using the default chip template.
  1125. mdChipsCtrl.enableChipEdit = false;
  1126. }
  1127. mdChipsCtrl.chipContentsTemplate = chipContentsTemplate;
  1128. mdChipsCtrl.chipRemoveTemplate = chipRemoveTemplate;
  1129. mdChipsCtrl.chipInputTemplate = chipInputTemplate;
  1130. mdChipsCtrl.mdCloseIcon = $$mdSvgRegistry.mdClose;
  1131. element
  1132. .attr({ 'aria-hidden': true, tabindex: -1 })
  1133. .on('focus', function () { mdChipsCtrl.onFocus(); });
  1134. if (attr.ngModel) {
  1135. mdChipsCtrl.configureNgModel(element.controller('ngModel'));
  1136. // If an `md-transform-chip` attribute was set, tell the controller to use the expression
  1137. // before appending chips.
  1138. if (attrs.mdTransformChip) mdChipsCtrl.useTransformChipExpression();
  1139. // If an `md-on-append` attribute was set, tell the controller to use the expression
  1140. // when appending chips.
  1141. //
  1142. // DEPRECATED: Will remove in official 1.0 release
  1143. if (attrs.mdOnAppend) mdChipsCtrl.useOnAppendExpression();
  1144. // If an `md-on-add` attribute was set, tell the controller to use the expression
  1145. // when adding chips.
  1146. if (attrs.mdOnAdd) mdChipsCtrl.useOnAddExpression();
  1147. // If an `md-on-remove` attribute was set, tell the controller to use the expression
  1148. // when removing chips.
  1149. if (attrs.mdOnRemove) mdChipsCtrl.useOnRemoveExpression();
  1150. // If an `md-on-select` attribute was set, tell the controller to use the expression
  1151. // when selecting chips.
  1152. if (attrs.mdOnSelect) mdChipsCtrl.useOnSelectExpression();
  1153. // The md-autocomplete and input elements won't be compiled until after this directive
  1154. // is complete (due to their nested nature). Wait a tick before looking for them to
  1155. // configure the controller.
  1156. if (chipInputTemplate != templates.input) {
  1157. // The autocomplete will not appear until the readonly attribute is not true (i.e.
  1158. // false or undefined), so we have to watch the readonly and then on the next tick
  1159. // after the chip transclusion has run, we can configure the autocomplete and user
  1160. // input.
  1161. scope.$watch('$mdChipsCtrl.readonly', function(readonly) {
  1162. if (!readonly) {
  1163. $mdUtil.nextTick(function(){
  1164. if (chipInputTemplate.indexOf('<md-autocomplete') === 0) {
  1165. var autocompleteEl = element.find('md-autocomplete');
  1166. mdChipsCtrl.configureAutocomplete(autocompleteEl.controller('mdAutocomplete'));
  1167. }
  1168. mdChipsCtrl.configureUserInput(element.find('input'));
  1169. });
  1170. }
  1171. });
  1172. }
  1173. // At the next tick, if we find an input, make sure it has the md-input class
  1174. $mdUtil.nextTick(function() {
  1175. var input = element.find('input');
  1176. input && input.toggleClass('md-input', true);
  1177. });
  1178. }
  1179. // Compile with the parent's scope and prepend any static chips to the wrapper.
  1180. if (staticChips.length > 0) {
  1181. var compiledStaticChips = $compile(staticChips.clone())(scope.$parent);
  1182. $timeout(function() { element.find('md-chips-wrap').prepend(compiledStaticChips); });
  1183. }
  1184. };
  1185. }
  1186. function getTemplates() {
  1187. return {
  1188. chips: $mdUtil.processTemplate(MD_CHIPS_TEMPLATE),
  1189. input: $mdUtil.processTemplate(CHIP_INPUT_TEMPLATE),
  1190. default: $mdUtil.processTemplate(CHIP_DEFAULT_TEMPLATE),
  1191. remove: $mdUtil.processTemplate(CHIP_REMOVE_TEMPLATE)
  1192. };
  1193. }
  1194. }
  1195. angular
  1196. .module('material.components.chips')
  1197. .controller('MdContactChipsCtrl', MdContactChipsCtrl);
  1198. /**
  1199. * Controller for the MdContactChips component
  1200. * @constructor
  1201. */
  1202. function MdContactChipsCtrl () {
  1203. /** @type {Object} */
  1204. this.selectedItem = null;
  1205. /** @type {string} */
  1206. this.searchText = '';
  1207. }
  1208. MdContactChipsCtrl.prototype.queryContact = function(searchText) {
  1209. var results = this.contactQuery({'$query': searchText});
  1210. return this.filterSelected ?
  1211. results.filter(angular.bind(this, this.filterSelectedContacts)) : results;
  1212. };
  1213. MdContactChipsCtrl.prototype.itemName = function(item) {
  1214. return item[this.contactName];
  1215. };
  1216. MdContactChipsCtrl.prototype.filterSelectedContacts = function(contact) {
  1217. return this.contacts.indexOf(contact) == -1;
  1218. };
  1219. MdContactChips.$inject = ["$mdTheming", "$mdUtil"];angular
  1220. .module('material.components.chips')
  1221. .directive('mdContactChips', MdContactChips);
  1222. /**
  1223. * @ngdoc directive
  1224. * @name mdContactChips
  1225. * @module material.components.chips
  1226. *
  1227. * @description
  1228. * `<md-contact-chips>` is an input component based on `md-chips` and makes use of an
  1229. * `md-autocomplete` element. The component allows the caller to supply a query expression which
  1230. * returns a list of possible contacts. The user can select one of these and add it to the list of
  1231. * chips.
  1232. *
  1233. * You may also use the `md-highlight-text` directive along with its parameters to control the
  1234. * appearance of the matched text inside of the contacts' autocomplete popup.
  1235. *
  1236. * @param {string=|object=} ng-model A model to bind the list of items to
  1237. * @param {string=} placeholder Placeholder text that will be forwarded to the input.
  1238. * @param {string=} secondary-placeholder Placeholder text that will be forwarded to the input,
  1239. * displayed when there is at least on item in the list
  1240. * @param {expression} md-contacts An expression expected to return contacts matching the search
  1241. * test, `$query`. If this expression involves a promise, a loading bar is displayed while
  1242. * waiting for it to resolve.
  1243. * @param {string} md-contact-name The field name of the contact object representing the
  1244. * contact's name.
  1245. * @param {string} md-contact-email The field name of the contact object representing the
  1246. * contact's email address.
  1247. * @param {string} md-contact-image The field name of the contact object representing the
  1248. * contact's image.
  1249. *
  1250. *
  1251. * @param {expression=} filter-selected Whether to filter selected contacts from the list of
  1252. * suggestions shown in the autocomplete. This attribute has been removed but may come back.
  1253. *
  1254. *
  1255. *
  1256. * @usage
  1257. * <hljs lang="html">
  1258. * <md-contact-chips
  1259. * ng-model="ctrl.contacts"
  1260. * md-contacts="ctrl.querySearch($query)"
  1261. * md-contact-name="name"
  1262. * md-contact-image="image"
  1263. * md-contact-email="email"
  1264. * placeholder="To">
  1265. * </md-contact-chips>
  1266. * </hljs>
  1267. *
  1268. */
  1269. var MD_CONTACT_CHIPS_TEMPLATE = '\
  1270. <md-chips class="md-contact-chips"\
  1271. ng-model="$mdContactChipsCtrl.contacts"\
  1272. md-require-match="$mdContactChipsCtrl.requireMatch"\
  1273. md-autocomplete-snap>\
  1274. <md-autocomplete\
  1275. md-menu-class="md-contact-chips-suggestions"\
  1276. md-selected-item="$mdContactChipsCtrl.selectedItem"\
  1277. md-search-text="$mdContactChipsCtrl.searchText"\
  1278. md-items="item in $mdContactChipsCtrl.queryContact($mdContactChipsCtrl.searchText)"\
  1279. md-item-text="$mdContactChipsCtrl.itemName(item)"\
  1280. md-no-cache="true"\
  1281. md-autoselect\
  1282. placeholder="{{$mdContactChipsCtrl.contacts.length == 0 ?\
  1283. $mdContactChipsCtrl.placeholder : $mdContactChipsCtrl.secondaryPlaceholder}}">\
  1284. <div class="md-contact-suggestion">\
  1285. <img \
  1286. ng-src="{{item[$mdContactChipsCtrl.contactImage]}}"\
  1287. alt="{{item[$mdContactChipsCtrl.contactName]}}"\
  1288. ng-if="item[$mdContactChipsCtrl.contactImage]" />\
  1289. <span class="md-contact-name" md-highlight-text="$mdContactChipsCtrl.searchText"\
  1290. md-highlight-flags="{{$mdContactChipsCtrl.highlightFlags}}">\
  1291. {{item[$mdContactChipsCtrl.contactName]}}\
  1292. </span>\
  1293. <span class="md-contact-email" >{{item[$mdContactChipsCtrl.contactEmail]}}</span>\
  1294. </div>\
  1295. </md-autocomplete>\
  1296. <md-chip-template>\
  1297. <div class="md-contact-avatar">\
  1298. <img \
  1299. ng-src="{{$chip[$mdContactChipsCtrl.contactImage]}}"\
  1300. alt="{{$chip[$mdContactChipsCtrl.contactName]}}"\
  1301. ng-if="$chip[$mdContactChipsCtrl.contactImage]" />\
  1302. </div>\
  1303. <div class="md-contact-name">\
  1304. {{$chip[$mdContactChipsCtrl.contactName]}}\
  1305. </div>\
  1306. </md-chip-template>\
  1307. </md-chips>';
  1308. /**
  1309. * MDContactChips Directive Definition
  1310. *
  1311. * @param $mdTheming
  1312. * @returns {*}
  1313. * ngInject
  1314. */
  1315. function MdContactChips($mdTheming, $mdUtil) {
  1316. return {
  1317. template: function(element, attrs) {
  1318. return MD_CONTACT_CHIPS_TEMPLATE;
  1319. },
  1320. restrict: 'E',
  1321. controller: 'MdContactChipsCtrl',
  1322. controllerAs: '$mdContactChipsCtrl',
  1323. bindToController: true,
  1324. compile: compile,
  1325. scope: {
  1326. contactQuery: '&mdContacts',
  1327. placeholder: '@',
  1328. secondaryPlaceholder: '@',
  1329. contactName: '@mdContactName',
  1330. contactImage: '@mdContactImage',
  1331. contactEmail: '@mdContactEmail',
  1332. contacts: '=ngModel',
  1333. requireMatch: '=?mdRequireMatch',
  1334. highlightFlags: '@?mdHighlightFlags'
  1335. }
  1336. };
  1337. function compile(element, attr) {
  1338. return function postLink(scope, element, attrs, controllers) {
  1339. $mdUtil.initOptionalProperties(scope, attr);
  1340. $mdTheming(element);
  1341. element.attr('tabindex', '-1');
  1342. };
  1343. }
  1344. }
  1345. })(window, window.angular);