chips.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. /*!
  2. * Angular Material Design
  3. * https://github.com/angular/material
  4. * @license MIT
  5. * v0.11.4
  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. angular
  21. .module('material.components.chips')
  22. .directive('mdChip', MdChip);
  23. /**
  24. * @ngdoc directive
  25. * @name mdChip
  26. * @module material.components.chips
  27. *
  28. * @description
  29. * `<md-chip>` is a component used within `<md-chips>` and is responsible for rendering individual
  30. * chips.
  31. *
  32. *
  33. * @usage
  34. * <hljs lang="html">
  35. * <md-chip>{{$chip}}</md-chip>
  36. * </hljs>
  37. *
  38. */
  39. // This hint text is hidden within a chip but used by screen readers to
  40. // inform the user how they can interact with a chip.
  41. var DELETE_HINT_TEMPLATE = '\
  42. <span ng-if="!$mdChipsCtrl.readonly" class="md-visually-hidden">\
  43. {{$mdChipsCtrl.deleteHint}}\
  44. </span>';
  45. /**
  46. * MDChip Directive Definition
  47. *
  48. * @param $mdTheming
  49. * @param $mdInkRipple
  50. * ngInject
  51. */
  52. function MdChip($mdTheming, $mdUtil) {
  53. var hintTemplate = $mdUtil.processTemplate(DELETE_HINT_TEMPLATE);
  54. return {
  55. restrict: 'E',
  56. require: '^?mdChips',
  57. compile: compile
  58. };
  59. function compile(element, attr) {
  60. // Append the delete template
  61. element.append($mdUtil.processTemplate(hintTemplate));
  62. return function postLink(scope, element, attr, ctrl) {
  63. element.addClass('md-chip');
  64. $mdTheming(element);
  65. if (ctrl) angular.element(element[0].querySelector('.md-chip-content'))
  66. .on('blur', function () {
  67. ctrl.selectedChip = -1;
  68. });
  69. };
  70. }
  71. }
  72. MdChip.$inject = ["$mdTheming", "$mdUtil"];
  73. angular
  74. .module('material.components.chips')
  75. .directive('mdChipRemove', MdChipRemove);
  76. /**
  77. * @ngdoc directive
  78. * @name mdChipRemove
  79. * @module material.components.chips
  80. *
  81. * @description
  82. * `<md-chip-remove>`
  83. * Designates an element to be used as the delete button for a chip. This
  84. * element is passed as a child of the `md-chips` element.
  85. *
  86. * @usage
  87. * <hljs lang="html">
  88. * <md-chips><button md-chip-remove>DEL</button></md-chips>
  89. * </hljs>
  90. */
  91. /**
  92. * MdChipRemove Directive Definition.
  93. *
  94. * @param $compile
  95. * @param $timeout
  96. * @returns {{restrict: string, require: string[], link: Function, scope: boolean}}
  97. * @constructor
  98. */
  99. function MdChipRemove ($timeout) {
  100. return {
  101. restrict: 'A',
  102. require: '^mdChips',
  103. scope: false,
  104. link: postLink
  105. };
  106. function postLink(scope, element, attr, ctrl) {
  107. element.on('click', function(event) {
  108. scope.$apply(function() {
  109. ctrl.removeChip(scope.$$replacedScope.$index);
  110. });
  111. });
  112. // Child elements aren't available until after a $timeout tick as they are hidden by an
  113. // `ng-if`. see http://goo.gl/zIWfuw
  114. $timeout(function() {
  115. element.attr({ tabindex: -1, ariaHidden: true });
  116. element.find('button').attr('tabindex', '-1');
  117. });
  118. }
  119. }
  120. MdChipRemove.$inject = ["$timeout"];
  121. angular
  122. .module('material.components.chips')
  123. .directive('mdChipTransclude', MdChipTransclude);
  124. function MdChipTransclude ($compile) {
  125. return {
  126. restrict: 'EA',
  127. terminal: true,
  128. link: link,
  129. scope: false
  130. };
  131. function link (scope, element, attr) {
  132. var ctrl = scope.$parent.$mdChipsCtrl,
  133. newScope = ctrl.parent.$new(false, ctrl.parent);
  134. newScope.$$replacedScope = scope;
  135. newScope.$chip = scope.$chip;
  136. newScope.$index = scope.$index;
  137. newScope.$mdChipsCtrl = ctrl;
  138. var newHtml = ctrl.$scope.$eval(attr.mdChipTransclude);
  139. element.html(newHtml);
  140. $compile(element.contents())(newScope);
  141. }
  142. }
  143. MdChipTransclude.$inject = ["$compile"];
  144. angular
  145. .module('material.components.chips')
  146. .controller('MdChipsCtrl', MdChipsCtrl);
  147. /**
  148. * Controller for the MdChips component. Responsible for adding to and
  149. * removing from the list of chips, marking chips as selected, and binding to
  150. * the models of various input components.
  151. *
  152. * @param $scope
  153. * @param $mdConstant
  154. * @param $log
  155. * @param $element
  156. * @constructor
  157. */
  158. function MdChipsCtrl ($scope, $mdConstant, $log, $element, $timeout) {
  159. /** @type {$timeout} **/
  160. this.$timeout = $timeout;
  161. /** @type {Object} */
  162. this.$mdConstant = $mdConstant;
  163. /** @type {angular.$scope} */
  164. this.$scope = $scope;
  165. /** @type {angular.$scope} */
  166. this.parent = $scope.$parent;
  167. /** @type {$log} */
  168. this.$log = $log;
  169. /** @type {$element} */
  170. this.$element = $element;
  171. /** @type {angular.NgModelController} */
  172. this.ngModelCtrl = null;
  173. /** @type {angular.NgModelController} */
  174. this.userInputNgModelCtrl = null;
  175. /** @type {Element} */
  176. this.userInputElement = null;
  177. /** @type {Array.<Object>} */
  178. this.items = [];
  179. /** @type {number} */
  180. this.selectedChip = -1;
  181. /** @type {boolean} */
  182. this.hasAutocomplete = false;
  183. /**
  184. * Hidden hint text for how to delete a chip. Used to give context to screen readers.
  185. * @type {string}
  186. */
  187. this.deleteHint = 'Press delete to remove this chip.';
  188. /**
  189. * Hidden label for the delete button. Used to give context to screen readers.
  190. * @type {string}
  191. */
  192. this.deleteButtonLabel = 'Remove';
  193. /**
  194. * Model used by the input element.
  195. * @type {string}
  196. */
  197. this.chipBuffer = '';
  198. /**
  199. * Whether to use the onAppend expression to transform the chip buffer
  200. * before appending it to the list.
  201. * @type {boolean}
  202. */
  203. this.useOnAppend = false;
  204. /**
  205. * Whether to use the onSelect expression to notify the component's user
  206. * after selecting a chip from the list.
  207. * @type {boolean}
  208. */
  209. this.useOnSelect = false;
  210. }
  211. MdChipsCtrl.$inject = ["$scope", "$mdConstant", "$log", "$element", "$timeout"];
  212. /**
  213. * Handles the keydown event on the input element: <enter> appends the
  214. * buffer to the chip list, while backspace removes the last chip in the list
  215. * if the current buffer is empty.
  216. * @param event
  217. */
  218. MdChipsCtrl.prototype.inputKeydown = function(event) {
  219. var chipBuffer = this.getChipBuffer();
  220. switch (event.keyCode) {
  221. case this.$mdConstant.KEY_CODE.ENTER:
  222. if ((this.hasAutocomplete && this.requireMatch) || !chipBuffer) break;
  223. event.preventDefault();
  224. this.appendChip(chipBuffer);
  225. this.resetChipBuffer();
  226. break;
  227. case this.$mdConstant.KEY_CODE.BACKSPACE:
  228. if (chipBuffer) break;
  229. event.preventDefault();
  230. event.stopPropagation();
  231. if (this.items.length) this.selectAndFocusChipSafe(this.items.length - 1);
  232. break;
  233. }
  234. };
  235. /**
  236. * Handles the keydown event on the chip elements: backspace removes the selected chip, arrow
  237. * keys switch which chips is active
  238. * @param event
  239. */
  240. MdChipsCtrl.prototype.chipKeydown = function (event) {
  241. if (this.getChipBuffer()) return;
  242. switch (event.keyCode) {
  243. case this.$mdConstant.KEY_CODE.BACKSPACE:
  244. case this.$mdConstant.KEY_CODE.DELETE:
  245. if (this.selectedChip < 0) return;
  246. event.preventDefault();
  247. this.removeAndSelectAdjacentChip(this.selectedChip);
  248. break;
  249. case this.$mdConstant.KEY_CODE.LEFT_ARROW:
  250. event.preventDefault();
  251. if (this.selectedChip < 0) this.selectedChip = this.items.length;
  252. if (this.items.length) this.selectAndFocusChipSafe(this.selectedChip - 1);
  253. break;
  254. case this.$mdConstant.KEY_CODE.RIGHT_ARROW:
  255. event.preventDefault();
  256. this.selectAndFocusChipSafe(this.selectedChip + 1);
  257. break;
  258. case this.$mdConstant.KEY_CODE.ESCAPE:
  259. case this.$mdConstant.KEY_CODE.TAB:
  260. if (this.selectedChip < 0) return;
  261. event.preventDefault();
  262. this.onFocus();
  263. break;
  264. }
  265. };
  266. /**
  267. * Get the input's placeholder - uses `placeholder` when list is empty and `secondary-placeholder`
  268. * when the list is non-empty. If `secondary-placeholder` is not provided, `placeholder` is used
  269. * always.
  270. */
  271. MdChipsCtrl.prototype.getPlaceholder = function() {
  272. // Allow `secondary-placeholder` to be blank.
  273. var useSecondary = (this.items.length &&
  274. (this.secondaryPlaceholder == '' || this.secondaryPlaceholder));
  275. return useSecondary ? this.placeholder : this.secondaryPlaceholder;
  276. };
  277. /**
  278. * Removes chip at {@code index} and selects the adjacent chip.
  279. * @param index
  280. */
  281. MdChipsCtrl.prototype.removeAndSelectAdjacentChip = function(index) {
  282. var selIndex = this.getAdjacentChipIndex(index);
  283. this.removeChip(index);
  284. this.$timeout(angular.bind(this, function () {
  285. this.selectAndFocusChipSafe(selIndex);
  286. }));
  287. };
  288. /**
  289. * Sets the selected chip index to -1.
  290. */
  291. MdChipsCtrl.prototype.resetSelectedChip = function() {
  292. this.selectedChip = -1;
  293. };
  294. /**
  295. * Gets the index of an adjacent chip to select after deletion. Adjacency is
  296. * determined as the next chip in the list, unless the target chip is the
  297. * last in the list, then it is the chip immediately preceding the target. If
  298. * there is only one item in the list, -1 is returned (select none).
  299. * The number returned is the index to select AFTER the target has been
  300. * removed.
  301. * If the current chip is not selected, then -1 is returned to select none.
  302. */
  303. MdChipsCtrl.prototype.getAdjacentChipIndex = function(index) {
  304. var len = this.items.length - 1;
  305. return (len == 0) ? -1 :
  306. (index == len) ? index -1 : index;
  307. };
  308. /**
  309. * Append the contents of the buffer to the chip list. This method will first
  310. * call out to the md-on-append method, if provided
  311. * @param newChip
  312. */
  313. MdChipsCtrl.prototype.appendChip = function(newChip) {
  314. if (this.useOnAppend && this.onAppend) {
  315. newChip = this.onAppend({'$chip': newChip});
  316. }
  317. if (this.items.indexOf(newChip) + 1) return;
  318. this.items.push(newChip);
  319. };
  320. /**
  321. * Sets whether to use the md-on-append expression. This expression is
  322. * bound to scope and controller in {@code MdChipsDirective} as
  323. * {@code onAppend}. Due to the nature of directive scope bindings, the
  324. * controller cannot know on its own/from the scope whether an expression was
  325. * actually provided.
  326. */
  327. MdChipsCtrl.prototype.useOnAppendExpression = function() {
  328. this.useOnAppend = true;
  329. };
  330. /**
  331. * Sets whether to use the md-on-remove expression. This expression is
  332. * bound to scope and controller in {@code MdChipsDirective} as
  333. * {@code onRemove}. Due to the nature of directive scope bindings, the
  334. * controller cannot know on its own/from the scope whether an expression was
  335. * actually provided.
  336. */
  337. MdChipsCtrl.prototype.useOnRemoveExpression = function() {
  338. this.useOnRemove = true;
  339. };
  340. /*
  341. * Sets whether to use the md-on-select expression. This expression is
  342. * bound to scope and controller in {@code MdChipsDirective} as
  343. * {@code onSelect}. Due to the nature of directive scope bindings, the
  344. * controller cannot know on its own/from the scope whether an expression was
  345. * actually provided.
  346. */
  347. MdChipsCtrl.prototype.useOnSelectExpression = function() {
  348. this.useOnSelect = true;
  349. };
  350. /**
  351. * Gets the input buffer. The input buffer can be the model bound to the
  352. * default input item {@code this.chipBuffer}, the {@code selectedItem}
  353. * model of an {@code md-autocomplete}, or, through some magic, the model
  354. * bound to any inpput or text area element found within a
  355. * {@code md-input-container} element.
  356. * @return {Object|string}
  357. */
  358. MdChipsCtrl.prototype.getChipBuffer = function() {
  359. return !this.userInputElement ? this.chipBuffer :
  360. this.userInputNgModelCtrl ? this.userInputNgModelCtrl.$viewValue :
  361. this.userInputElement[0].value;
  362. };
  363. /**
  364. * Resets the input buffer for either the internal input or user provided input element.
  365. */
  366. MdChipsCtrl.prototype.resetChipBuffer = function() {
  367. if (this.userInputElement) {
  368. if (this.userInputNgModelCtrl) {
  369. this.userInputNgModelCtrl.$setViewValue('');
  370. this.userInputNgModelCtrl.$render();
  371. } else {
  372. this.userInputElement[0].value = '';
  373. }
  374. } else {
  375. this.chipBuffer = '';
  376. }
  377. };
  378. /**
  379. * Removes the chip at the given index.
  380. * @param index
  381. */
  382. MdChipsCtrl.prototype.removeChip = function(index) {
  383. var removed = this.items.splice(index, 1);
  384. if (removed && removed.length && this.useOnRemove && this.onRemove) {
  385. this.onRemove({ '$chip': removed[0], '$index': index });
  386. }
  387. };
  388. MdChipsCtrl.prototype.removeChipAndFocusInput = function (index) {
  389. this.removeChip(index);
  390. this.onFocus();
  391. };
  392. /**
  393. * Selects the chip at `index`,
  394. * @param index
  395. */
  396. MdChipsCtrl.prototype.selectAndFocusChipSafe = function(index) {
  397. if (!this.items.length) {
  398. this.selectChip(-1);
  399. this.onFocus();
  400. return;
  401. }
  402. if (index === this.items.length) return this.onFocus();
  403. index = Math.max(index, 0);
  404. index = Math.min(index, this.items.length - 1);
  405. this.selectChip(index);
  406. this.focusChip(index);
  407. };
  408. /**
  409. * Marks the chip at the given index as selected.
  410. * @param index
  411. */
  412. MdChipsCtrl.prototype.selectChip = function(index) {
  413. if (index >= -1 && index <= this.items.length) {
  414. this.selectedChip = index;
  415. // Fire the onSelect if provided
  416. if (this.useOnSelect && this.onSelect) {
  417. this.onSelect({'$chip': this.items[this.selectedChip] });
  418. }
  419. } else {
  420. this.$log.warn('Selected Chip index out of bounds; ignoring.');
  421. }
  422. };
  423. /**
  424. * Selects the chip at `index` and gives it focus.
  425. * @param index
  426. */
  427. MdChipsCtrl.prototype.selectAndFocusChip = function(index) {
  428. this.selectChip(index);
  429. if (index != -1) {
  430. this.focusChip(index);
  431. }
  432. };
  433. /**
  434. * Call `focus()` on the chip at `index`
  435. */
  436. MdChipsCtrl.prototype.focusChip = function(index) {
  437. this.$element[0].querySelector('md-chip[index="' + index + '"] .md-chip-content').focus();
  438. };
  439. /**
  440. * Configures the required interactions with the ngModel Controller.
  441. * Specifically, set {@code this.items} to the {@code NgModelCtrl#$viewVale}.
  442. * @param ngModelCtrl
  443. */
  444. MdChipsCtrl.prototype.configureNgModel = function(ngModelCtrl) {
  445. this.ngModelCtrl = ngModelCtrl;
  446. var self = this;
  447. ngModelCtrl.$render = function() {
  448. // model is updated. do something.
  449. self.items = self.ngModelCtrl.$viewValue;
  450. };
  451. };
  452. MdChipsCtrl.prototype.onFocus = function () {
  453. var input = this.$element[0].querySelector('input');
  454. input && input.focus();
  455. this.resetSelectedChip();
  456. };
  457. MdChipsCtrl.prototype.onInputFocus = function () {
  458. this.inputHasFocus = true;
  459. this.resetSelectedChip();
  460. };
  461. MdChipsCtrl.prototype.onInputBlur = function () {
  462. this.inputHasFocus = false;
  463. };
  464. /**
  465. * Configure event bindings on a user-provided input element.
  466. * @param inputElement
  467. */
  468. MdChipsCtrl.prototype.configureUserInput = function(inputElement) {
  469. this.userInputElement = inputElement;
  470. // Find the NgModelCtrl for the input element
  471. var ngModelCtrl = inputElement.controller('ngModel');
  472. // `.controller` will look in the parent as well.
  473. if (ngModelCtrl != this.ngModelCtrl) {
  474. this.userInputNgModelCtrl = ngModelCtrl;
  475. }
  476. var scope = this.$scope;
  477. var ctrl = this;
  478. // Run all of the events using evalAsync because a focus may fire a blur in the same digest loop
  479. var scopeApplyFn = function(event, fn) {
  480. scope.$evalAsync(angular.bind(ctrl, fn, event));
  481. };
  482. // Bind to keydown and focus events of input
  483. inputElement
  484. .attr({ tabindex: 0 })
  485. .on('keydown', function(event) { scopeApplyFn(event, ctrl.inputKeydown) })
  486. .on('focus', function(event) { scopeApplyFn(event, ctrl.onInputFocus) })
  487. .on('blur', function(event) { scopeApplyFn(event, ctrl.onInputBlur) })
  488. };
  489. MdChipsCtrl.prototype.configureAutocomplete = function(ctrl) {
  490. if ( ctrl ){
  491. this.hasAutocomplete = true;
  492. ctrl.registerSelectedItemWatcher(angular.bind(this, function (item) {
  493. if (item) {
  494. this.appendChip(item);
  495. this.resetChipBuffer();
  496. }
  497. }));
  498. this.$element.find('input')
  499. .on('focus',angular.bind(this, this.onInputFocus) )
  500. .on('blur', angular.bind(this, this.onInputBlur) );
  501. }
  502. };
  503. MdChipsCtrl.prototype.hasFocus = function () {
  504. return this.inputHasFocus || this.selectedChip >= 0;
  505. };
  506. angular
  507. .module('material.components.chips')
  508. .directive('mdChips', MdChips);
  509. /**
  510. * @ngdoc directive
  511. * @name mdChips
  512. * @module material.components.chips
  513. *
  514. * @description
  515. * `<md-chips>` is an input component for building lists of strings or objects. The list items are
  516. * displayed as 'chips'. This component can make use of an `<input>` element or an
  517. * `<md-autocomplete>` element.
  518. *
  519. * ### Custom templates
  520. * A custom template may be provided to render the content of each chip. This is achieved by
  521. * specifying an `<md-chip-template>` element containing the custom content as a child of
  522. * `<md-chips>`.
  523. *
  524. * Note: Any attributes on
  525. * `<md-chip-template>` will be dropped as only the innerHTML is used for the chip template. The
  526. * variables `$chip` and `$index` are available in the scope of `<md-chip-template>`, representing
  527. * the chip object and its index in the list of chips, respectively.
  528. * To override the chip delete control, include an element (ideally a button) with the attribute
  529. * `md-chip-remove`. A click listener to remove the chip will be added automatically. The element
  530. * is also placed as a sibling to the chip content (on which there are also click listeners) to
  531. * avoid a nested ng-click situation.
  532. *
  533. * <h3> Pending Features </h3>
  534. * <ul style="padding-left:20px;">
  535. *
  536. * <ul>Style
  537. * <li>Colours for hover, press states (ripple?).</li>
  538. * </ul>
  539. *
  540. * <ul>Validation
  541. * <li>allow a validation callback</li>
  542. * <li>hilighting style for invalid chips</li>
  543. * </ul>
  544. *
  545. * <ul>Item mutation
  546. * <li>Support `
  547. * <md-chip-edit>` template, show/hide the edit element on tap/click? double tap/double
  548. * click?
  549. * </li>
  550. * </ul>
  551. *
  552. * <ul>Truncation and Disambiguation (?)
  553. * <li>Truncate chip text where possible, but do not truncate entries such that two are
  554. * indistinguishable.</li>
  555. * </ul>
  556. *
  557. * <ul>Drag and Drop
  558. * <li>Drag and drop chips between related `<md-chips>` elements.
  559. * </li>
  560. * </ul>
  561. * </ul>
  562. *
  563. * <span style="font-size:.8em;text-align:center">
  564. * Warning: This component is a WORK IN PROGRESS. If you use it now,
  565. * it will probably break on you in the future.
  566. * </span>
  567. *
  568. * @param {string=|object=} ng-model A model to bind the list of items to
  569. * @param {string=} placeholder Placeholder text that will be forwarded to the input.
  570. * @param {string=} secondary-placeholder Placeholder text that will be forwarded to the input,
  571. * displayed when there is at least on item in the list
  572. * @param {boolean=} readonly Disables list manipulation (deleting or adding list items), hiding
  573. * the input and delete buttons
  574. * @param {expression} md-on-append An expression that when called expects you to return an object
  575. * representation of the chip input string.
  576. * @param {expression=} md-on-remove An expression which will be called when a chip has been
  577. * removed.
  578. * @param {expression=} md-on-select An expression which will be called when a chip is selected.
  579. * @param {string=} delete-hint A string read by screen readers instructing users that pressing
  580. * the delete key will remove the chip.
  581. * @param {string=} delete-button-label A label for the delete button. Also hidden and read by
  582. * screen readers.
  583. *
  584. * @usage
  585. * <hljs lang="html">
  586. * <md-chips
  587. * ng-model="myItems"
  588. * placeholder="Add an item"
  589. * readonly="isReadOnly">
  590. * </md-chips>
  591. * </hljs>
  592. *
  593. */
  594. var MD_CHIPS_TEMPLATE = '\
  595. <md-chips-wrap\
  596. ng-if="!$mdChipsCtrl.readonly || $mdChipsCtrl.items.length > 0"\
  597. ng-keydown="$mdChipsCtrl.chipKeydown($event)"\
  598. ng-class="{ \'md-focused\': $mdChipsCtrl.hasFocus(), \'md-readonly\': !$mdChipsCtrl.ngModelCtrl }"\
  599. class="md-chips">\
  600. <md-chip ng-repeat="$chip in $mdChipsCtrl.items"\
  601. index="{{$index}}"\
  602. ng-class="{\'md-focused\': $mdChipsCtrl.selectedChip == $index, \'md-readonly\': $mdChipsCtrl.readonly}">\
  603. <div class="md-chip-content"\
  604. tabindex="-1"\
  605. aria-hidden="true"\
  606. ng-focus="!$mdChipsCtrl.readonly && $mdChipsCtrl.selectChip($index)"\
  607. md-chip-transclude="$mdChipsCtrl.chipContentsTemplate"></div>\
  608. <div ng-if="!$mdChipsCtrl.readonly"\
  609. class="md-chip-remove-container"\
  610. md-chip-transclude="$mdChipsCtrl.chipRemoveTemplate"></div>\
  611. </md-chip>\
  612. <div ng-if="!$mdChipsCtrl.readonly && $mdChipsCtrl.ngModelCtrl"\
  613. class="md-chip-input-container"\
  614. md-chip-transclude="$mdChipsCtrl.chipInputTemplate"></div>\
  615. </div>\
  616. </md-chips-wrap>';
  617. var CHIP_INPUT_TEMPLATE = '\
  618. <input\
  619. tabindex="0"\
  620. placeholder="{{$mdChipsCtrl.getPlaceholder()}}"\
  621. aria-label="{{$mdChipsCtrl.getPlaceholder()}}"\
  622. ng-model="$mdChipsCtrl.chipBuffer"\
  623. ng-focus="$mdChipsCtrl.onInputFocus()"\
  624. ng-blur="$mdChipsCtrl.onInputBlur()"\
  625. ng-keydown="$mdChipsCtrl.inputKeydown($event)">';
  626. var CHIP_DEFAULT_TEMPLATE = '\
  627. <span>{{$chip}}</span>';
  628. var CHIP_REMOVE_TEMPLATE = '\
  629. <button\
  630. class="md-chip-remove"\
  631. ng-if="!$mdChipsCtrl.readonly"\
  632. ng-click="$mdChipsCtrl.removeChipAndFocusInput($$replacedScope.$index)"\
  633. type="button"\
  634. aria-hidden="true"\
  635. tabindex="-1">\
  636. <md-icon md-svg-icon="md-close"></md-icon>\
  637. <span class="md-visually-hidden">\
  638. {{$mdChipsCtrl.deleteButtonLabel}}\
  639. </span>\
  640. </button>';
  641. /**
  642. * MDChips Directive Definition
  643. */
  644. function MdChips ($mdTheming, $mdUtil, $compile, $log, $timeout) {
  645. // Run our templates through $mdUtil.processTemplate() to allow custom start/end symbols
  646. var templates = getTemplates();
  647. return {
  648. template: function(element, attrs) {
  649. // Clone the element into an attribute. By prepending the attribute
  650. // name with '$', Angular won't write it into the DOM. The cloned
  651. // element propagates to the link function via the attrs argument,
  652. // where various contained-elements can be consumed.
  653. attrs['$mdUserTemplate'] = element.clone();
  654. return templates.chips;
  655. },
  656. require: ['mdChips'],
  657. restrict: 'E',
  658. controller: 'MdChipsCtrl',
  659. controllerAs: '$mdChipsCtrl',
  660. bindToController: true,
  661. compile: compile,
  662. scope: {
  663. readonly: '=readonly',
  664. placeholder: '@',
  665. secondaryPlaceholder: '@',
  666. onAppend: '&mdOnAppend',
  667. onRemove: '&mdOnRemove',
  668. onSelect: '&mdOnSelect',
  669. deleteHint: '@',
  670. deleteButtonLabel: '@',
  671. requireMatch: '=?mdRequireMatch'
  672. }
  673. };
  674. /**
  675. * Builds the final template for `md-chips` and returns the postLink function.
  676. *
  677. * Building the template involves 3 key components:
  678. * static chips
  679. * chip template
  680. * input control
  681. *
  682. * If no `ng-model` is provided, only the static chip work needs to be done.
  683. *
  684. * If no user-passed `md-chip-template` exists, the default template is used. This resulting
  685. * template is appended to the chip content element.
  686. *
  687. * The remove button may be overridden by passing an element with an md-chip-remove attribute.
  688. *
  689. * If an `input` or `md-autocomplete` element is provided by the caller, it is set aside for
  690. * transclusion later. The transclusion happens in `postLink` as the parent scope is required.
  691. * If no user input is provided, a default one is appended to the input container node in the
  692. * template.
  693. *
  694. * Static Chips (i.e. `md-chip` elements passed from the caller) are gathered and set aside for
  695. * transclusion in the `postLink` function.
  696. *
  697. *
  698. * @param element
  699. * @param attr
  700. * @returns {Function}
  701. */
  702. function compile(element, attr) {
  703. // Grab the user template from attr and reset the attribute to null.
  704. var userTemplate = attr['$mdUserTemplate'];
  705. attr['$mdUserTemplate'] = null;
  706. // Set the chip remove, chip contents and chip input templates. The link function will put
  707. // them on the scope for transclusion later.
  708. var chipRemoveTemplate = getTemplateByQuery('md-chips>*[md-chip-remove]') || templates.remove,
  709. chipContentsTemplate = getTemplateByQuery('md-chips>md-chip-template') || templates.default,
  710. chipInputTemplate = getTemplateByQuery('md-chips>md-autocomplete')
  711. || getTemplateByQuery('md-chips>input')
  712. || templates.input,
  713. staticChips = userTemplate.find('md-chip');
  714. // Warn of malformed template. See #2545
  715. if (userTemplate[0].querySelector('md-chip-template>*[md-chip-remove]')) {
  716. $log.warn('invalid placement of md-chip-remove within md-chip-template.');
  717. }
  718. function getTemplateByQuery (query) {
  719. if (!attr.ngModel) return;
  720. var element = userTemplate[0].querySelector(query);
  721. return element && element.outerHTML;
  722. }
  723. /**
  724. * Configures controller and transcludes.
  725. */
  726. return function postLink(scope, element, attrs, controllers) {
  727. $mdUtil.initOptionalProperties(scope, attr);
  728. $mdTheming(element);
  729. var mdChipsCtrl = controllers[0];
  730. mdChipsCtrl.chipContentsTemplate = chipContentsTemplate;
  731. mdChipsCtrl.chipRemoveTemplate = chipRemoveTemplate;
  732. mdChipsCtrl.chipInputTemplate = chipInputTemplate;
  733. element
  734. .attr({ ariaHidden: true, tabindex: -1 })
  735. .on('focus', function () { mdChipsCtrl.onFocus(); });
  736. if (attr.ngModel) {
  737. mdChipsCtrl.configureNgModel(element.controller('ngModel'));
  738. // If an `md-on-append` attribute was set, tell the controller to use the expression
  739. // when appending chips.
  740. if (attrs.mdOnAppend) mdChipsCtrl.useOnAppendExpression();
  741. // If an `md-on-remove` attribute was set, tell the controller to use the expression
  742. // when removing chips.
  743. if (attrs.mdOnRemove) mdChipsCtrl.useOnRemoveExpression();
  744. // If an `md-on-select` attribute was set, tell the controller to use the expression
  745. // when selecting chips.
  746. if (attrs.mdOnSelect) mdChipsCtrl.useOnSelectExpression();
  747. // The md-autocomplete and input elements won't be compiled until after this directive
  748. // is complete (due to their nested nature). Wait a tick before looking for them to
  749. // configure the controller.
  750. if (chipInputTemplate != templates.input) {
  751. // The autocomplete will not appear until the readonly attribute is not true (i.e.
  752. // false or undefined), so we have to watch the readonly and then on the next tick
  753. // after the chip transclusion has run, we can configure the autocomplete and user
  754. // input.
  755. scope.$watch('$mdChipsCtrl.readonly', function(readonly) {
  756. if (!readonly) {
  757. $mdUtil.nextTick(function(){
  758. if (chipInputTemplate.indexOf('<md-autocomplete') === 0)
  759. mdChipsCtrl
  760. .configureAutocomplete(element.find('md-autocomplete')
  761. .controller('mdAutocomplete'));
  762. mdChipsCtrl.configureUserInput(element.find('input'));
  763. });
  764. }
  765. });
  766. }
  767. }
  768. // Compile with the parent's scope and prepend any static chips to the wrapper.
  769. if (staticChips.length > 0) {
  770. var compiledStaticChips = $compile(staticChips.clone())(scope.$parent);
  771. $timeout(function() { element.find('md-chips-wrap').prepend(compiledStaticChips); });
  772. }
  773. };
  774. }
  775. function getTemplates() {
  776. return {
  777. chips: $mdUtil.processTemplate(MD_CHIPS_TEMPLATE),
  778. input: $mdUtil.processTemplate(CHIP_INPUT_TEMPLATE),
  779. default: $mdUtil.processTemplate(CHIP_DEFAULT_TEMPLATE),
  780. remove: $mdUtil.processTemplate(CHIP_REMOVE_TEMPLATE)
  781. };
  782. }
  783. }
  784. MdChips.$inject = ["$mdTheming", "$mdUtil", "$compile", "$log", "$timeout"];
  785. angular
  786. .module('material.components.chips')
  787. .controller('MdContactChipsCtrl', MdContactChipsCtrl);
  788. /**
  789. * Controller for the MdContactChips component
  790. * @constructor
  791. */
  792. function MdContactChipsCtrl () {
  793. /** @type {Object} */
  794. this.selectedItem = null;
  795. /** @type {string} */
  796. this.searchText = '';
  797. }
  798. MdContactChipsCtrl.prototype.queryContact = function(searchText) {
  799. var results = this.contactQuery({'$query': searchText});
  800. return this.filterSelected ?
  801. results.filter(angular.bind(this, this.filterSelectedContacts)) : results;
  802. };
  803. MdContactChipsCtrl.prototype.itemName = function(item) {
  804. return item[this.contactName];
  805. };
  806. MdContactChipsCtrl.prototype.filterSelectedContacts = function(contact) {
  807. return this.contacts.indexOf(contact) == -1;
  808. };
  809. angular
  810. .module('material.components.chips')
  811. .directive('mdContactChips', MdContactChips);
  812. /**
  813. * @ngdoc directive
  814. * @name mdContactChips
  815. * @module material.components.chips
  816. *
  817. * @description
  818. * `<md-contact-chips>` is an input component based on `md-chips` and makes use of an
  819. * `md-autocomplete` element. The component allows the caller to supply a query expression which
  820. * returns a list of possible contacts. The user can select one of these and add it to the list of
  821. * chips.
  822. *
  823. * You may also use the `md-highlight-text` directive along with it's parameters to control the
  824. * appearance of the matched text inside of the contacts' autocomplete popup.
  825. *
  826. * @param {string=|object=} ng-model A model to bind the list of items to
  827. * @param {string=} placeholder Placeholder text that will be forwarded to the input.
  828. * @param {string=} secondary-placeholder Placeholder text that will be forwarded to the input,
  829. * displayed when there is at least on item in the list
  830. * @param {expression} md-contacts An expression expected to return contacts matching the search
  831. * test, `$query`.
  832. * @param {string} md-contact-name The field name of the contact object representing the
  833. * contact's name.
  834. * @param {string} md-contact-email The field name of the contact object representing the
  835. * contact's email address.
  836. * @param {string} md-contact-image The field name of the contact object representing the
  837. * contact's image.
  838. *
  839. *
  840. * // The following attribute has been removed but may come back.
  841. * @param {expression=} filter-selected Whether to filter selected contacts from the list of
  842. * suggestions shown in the autocomplete.
  843. *
  844. *
  845. *
  846. * @usage
  847. * <hljs lang="html">
  848. * <md-contact-chips
  849. * ng-model="ctrl.contacts"
  850. * md-contacts="ctrl.querySearch($query)"
  851. * md-contact-name="name"
  852. * md-contact-image="image"
  853. * md-contact-email="email"
  854. * placeholder="To">
  855. * </md-contact-chips>
  856. * </hljs>
  857. *
  858. */
  859. var MD_CONTACT_CHIPS_TEMPLATE = '\
  860. <md-chips class="md-contact-chips"\
  861. ng-model="$mdContactChipsCtrl.contacts"\
  862. md-require-match="$mdContactChipsCtrl.requireMatch"\
  863. md-autocomplete-snap>\
  864. <md-autocomplete\
  865. md-menu-class="md-contact-chips-suggestions"\
  866. md-selected-item="$mdContactChipsCtrl.selectedItem"\
  867. md-search-text="$mdContactChipsCtrl.searchText"\
  868. md-items="item in $mdContactChipsCtrl.queryContact($mdContactChipsCtrl.searchText)"\
  869. md-item-text="$mdContactChipsCtrl.itemName(item)"\
  870. md-no-cache="true"\
  871. md-autoselect\
  872. placeholder="{{$mdContactChipsCtrl.contacts.length == 0 ?\
  873. $mdContactChipsCtrl.placeholder : $mdContactChipsCtrl.secondaryPlaceholder}}">\
  874. <div class="md-contact-suggestion">\
  875. <img \
  876. ng-src="{{item[$mdContactChipsCtrl.contactImage]}}"\
  877. alt="{{item[$mdContactChipsCtrl.contactName]}}"\
  878. ng-if="item[$mdContactChipsCtrl.contactImage]" />\
  879. <span class="md-contact-name" md-highlight-text="$mdContactChipsCtrl.searchText"\
  880. md-highlight-flags="{{$mdContactChipsCtrl.highlightFlags}}">\
  881. {{item[$mdContactChipsCtrl.contactName]}}\
  882. </span>\
  883. <span class="md-contact-email" >{{item[$mdContactChipsCtrl.contactEmail]}}</span>\
  884. </div>\
  885. </md-autocomplete>\
  886. <md-chip-template>\
  887. <div class="md-contact-avatar">\
  888. <img \
  889. ng-src="{{$chip[$mdContactChipsCtrl.contactImage]}}"\
  890. alt="{{$chip[$mdContactChipsCtrl.contactName]}}"\
  891. ng-if="$chip[$mdContactChipsCtrl.contactImage]" />\
  892. </div>\
  893. <div class="md-contact-name">\
  894. {{$chip[$mdContactChipsCtrl.contactName]}}\
  895. </div>\
  896. </md-chip-template>\
  897. </md-chips>';
  898. /**
  899. * MDContactChips Directive Definition
  900. *
  901. * @param $mdTheming
  902. * @returns {*}
  903. * ngInject
  904. */
  905. function MdContactChips($mdTheming, $mdUtil) {
  906. return {
  907. template: function(element, attrs) {
  908. return MD_CONTACT_CHIPS_TEMPLATE;
  909. },
  910. restrict: 'E',
  911. controller: 'MdContactChipsCtrl',
  912. controllerAs: '$mdContactChipsCtrl',
  913. bindToController: true,
  914. compile: compile,
  915. scope: {
  916. contactQuery: '&mdContacts',
  917. placeholder: '@',
  918. secondaryPlaceholder: '@',
  919. contactName: '@mdContactName',
  920. contactImage: '@mdContactImage',
  921. contactEmail: '@mdContactEmail',
  922. contacts: '=ngModel',
  923. requireMatch: '=?mdRequireMatch',
  924. highlightFlags: '@?mdHighlightFlags'
  925. }
  926. };
  927. function compile(element, attr) {
  928. return function postLink(scope, element, attrs, controllers) {
  929. $mdUtil.initOptionalProperties(scope, attr);
  930. $mdTheming(element);
  931. element.attr('tabindex', '-1');
  932. };
  933. }
  934. }
  935. MdContactChips.$inject = ["$mdTheming", "$mdUtil"];
  936. })(window, window.angular);