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