chips.js 34 KB

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