chips.js 57 KB

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