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