select.js 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427
  1. /*!
  2. * ui-select
  3. * http://github.com/angular-ui/ui-select
  4. * Version: 0.19.7 - 2017-04-15T14:28:36.649Z
  5. * License: MIT
  6. */
  7. (function () {
  8. "use strict";
  9. var KEY = {
  10. TAB: 9,
  11. ENTER: 13,
  12. ESC: 27,
  13. SPACE: 32,
  14. LEFT: 37,
  15. UP: 38,
  16. RIGHT: 39,
  17. DOWN: 40,
  18. SHIFT: 16,
  19. CTRL: 17,
  20. ALT: 18,
  21. PAGE_UP: 33,
  22. PAGE_DOWN: 34,
  23. HOME: 36,
  24. END: 35,
  25. BACKSPACE: 8,
  26. DELETE: 46,
  27. COMMAND: 91,
  28. MAP: { 91 : "COMMAND", 8 : "BACKSPACE" , 9 : "TAB" , 13 : "ENTER" , 16 : "SHIFT" , 17 : "CTRL" , 18 : "ALT" , 19 : "PAUSEBREAK" , 20 : "CAPSLOCK" , 27 : "ESC" , 32 : "SPACE" , 33 : "PAGE_UP", 34 : "PAGE_DOWN" , 35 : "END" , 36 : "HOME" , 37 : "LEFT" , 38 : "UP" , 39 : "RIGHT" , 40 : "DOWN" , 43 : "+" , 44 : "PRINTSCREEN" , 45 : "INSERT" , 46 : "DELETE", 48 : "0" , 49 : "1" , 50 : "2" , 51 : "3" , 52 : "4" , 53 : "5" , 54 : "6" , 55 : "7" , 56 : "8" , 57 : "9" , 59 : ";", 61 : "=" , 65 : "A" , 66 : "B" , 67 : "C" , 68 : "D" , 69 : "E" , 70 : "F" , 71 : "G" , 72 : "H" , 73 : "I" , 74 : "J" , 75 : "K" , 76 : "L", 77 : "M" , 78 : "N" , 79 : "O" , 80 : "P" , 81 : "Q" , 82 : "R" , 83 : "S" , 84 : "T" , 85 : "U" , 86 : "V" , 87 : "W" , 88 : "X" , 89 : "Y" , 90 : "Z", 96 : "0" , 97 : "1" , 98 : "2" , 99 : "3" , 100 : "4" , 101 : "5" , 102 : "6" , 103 : "7" , 104 : "8" , 105 : "9", 106 : "*" , 107 : "+" , 109 : "-" , 110 : "." , 111 : "/", 112 : "F1" , 113 : "F2" , 114 : "F3" , 115 : "F4" , 116 : "F5" , 117 : "F6" , 118 : "F7" , 119 : "F8" , 120 : "F9" , 121 : "F10" , 122 : "F11" , 123 : "F12", 144 : "NUMLOCK" , 145 : "SCROLLLOCK" , 186 : ";" , 187 : "=" , 188 : "," , 189 : "-" , 190 : "." , 191 : "/" , 192 : "`" , 219 : "[" , 220 : "\\" , 221 : "]" , 222 : "'"
  29. },
  30. isControl: function (e) {
  31. var k = e.which;
  32. switch (k) {
  33. case KEY.COMMAND:
  34. case KEY.SHIFT:
  35. case KEY.CTRL:
  36. case KEY.ALT:
  37. return true;
  38. }
  39. if (e.metaKey || e.ctrlKey || e.altKey) return true;
  40. return false;
  41. },
  42. isFunctionKey: function (k) {
  43. k = k.which ? k.which : k;
  44. return k >= 112 && k <= 123;
  45. },
  46. isVerticalMovement: function (k){
  47. return ~[KEY.UP, KEY.DOWN].indexOf(k);
  48. },
  49. isHorizontalMovement: function (k){
  50. return ~[KEY.LEFT,KEY.RIGHT,KEY.BACKSPACE,KEY.DELETE].indexOf(k);
  51. },
  52. toSeparator: function (k) {
  53. var sep = {ENTER:"\n",TAB:"\t",SPACE:" "}[k];
  54. if (sep) return sep;
  55. // return undefined for special keys other than enter, tab or space.
  56. // no way to use them to cut strings.
  57. return KEY[k] ? undefined : k;
  58. }
  59. };
  60. function isNil(value) {
  61. return angular.isUndefined(value) || value === null;
  62. }
  63. /**
  64. * Add querySelectorAll() to jqLite.
  65. *
  66. * jqLite find() is limited to lookups by tag name.
  67. * TODO This will change with future versions of AngularJS, to be removed when this happens
  68. *
  69. * See jqLite.find - why not use querySelectorAll? https://github.com/angular/angular.js/issues/3586
  70. * See feat(jqLite): use querySelectorAll instead of getElementsByTagName in jqLite.find https://github.com/angular/angular.js/pull/3598
  71. */
  72. if (angular.element.prototype.querySelectorAll === undefined) {
  73. angular.element.prototype.querySelectorAll = function(selector) {
  74. return angular.element(this[0].querySelectorAll(selector));
  75. };
  76. }
  77. /**
  78. * Add closest() to jqLite.
  79. */
  80. if (angular.element.prototype.closest === undefined) {
  81. angular.element.prototype.closest = function( selector) {
  82. var elem = this[0];
  83. var matchesSelector = elem.matches || elem.webkitMatchesSelector || elem.mozMatchesSelector || elem.msMatchesSelector;
  84. while (elem) {
  85. if (matchesSelector.bind(elem)(selector)) {
  86. return elem;
  87. } else {
  88. elem = elem.parentElement;
  89. }
  90. }
  91. return false;
  92. };
  93. }
  94. var latestId = 0;
  95. var uis = angular.module('ui.select', [])
  96. .constant('uiSelectConfig', {
  97. theme: 'bootstrap',
  98. searchEnabled: true,
  99. sortable: false,
  100. placeholder: '', // Empty by default, like HTML tag <select>
  101. refreshDelay: 1000, // In milliseconds
  102. closeOnSelect: true,
  103. skipFocusser: false,
  104. dropdownPosition: 'auto',
  105. removeSelected: true,
  106. resetSearchInput: true,
  107. generateId: function() {
  108. return latestId++;
  109. },
  110. appendToBody: false,
  111. spinnerEnabled: false,
  112. spinnerClass: 'glyphicon glyphicon-refresh ui-select-spin',
  113. backspaceReset: true
  114. })
  115. // See Rename minErr and make it accessible from outside https://github.com/angular/angular.js/issues/6913
  116. .service('uiSelectMinErr', function() {
  117. var minErr = angular.$$minErr('ui.select');
  118. return function() {
  119. var error = minErr.apply(this, arguments);
  120. var message = error.message.replace(new RegExp('\nhttp://errors.angularjs.org/.*'), '');
  121. return new Error(message);
  122. };
  123. })
  124. // Recreates old behavior of ng-transclude. Used internally.
  125. .directive('uisTranscludeAppend', function () {
  126. return {
  127. link: function (scope, element, attrs, ctrl, transclude) {
  128. transclude(scope, function (clone) {
  129. element.append(clone);
  130. });
  131. }
  132. };
  133. })
  134. /**
  135. * Highlights text that matches $select.search.
  136. *
  137. * Taken from AngularUI Bootstrap Typeahead
  138. * See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L340
  139. */
  140. .filter('highlight', function() {
  141. function escapeRegexp(queryToEscape) {
  142. return ('' + queryToEscape).replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
  143. }
  144. return function(matchItem, query) {
  145. return query && matchItem ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<span class="ui-select-highlight">$&</span>') : matchItem;
  146. };
  147. })
  148. /**
  149. * A read-only equivalent of jQuery's offset function: http://api.jquery.com/offset/
  150. *
  151. * Taken from AngularUI Bootstrap Position:
  152. * See https://github.com/angular-ui/bootstrap/blob/master/src/position/position.js#L70
  153. */
  154. .factory('uisOffset',
  155. ['$document', '$window',
  156. function ($document, $window) {
  157. return function(element) {
  158. var boundingClientRect = element[0].getBoundingClientRect();
  159. return {
  160. width: boundingClientRect.width || element.prop('offsetWidth'),
  161. height: boundingClientRect.height || element.prop('offsetHeight'),
  162. top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),
  163. left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)
  164. };
  165. };
  166. }]);
  167. /**
  168. * Debounces functions
  169. *
  170. * Taken from UI Bootstrap $$debounce source code
  171. * See https://github.com/angular-ui/bootstrap/blob/master/src/debounce/debounce.js
  172. *
  173. */
  174. uis.factory('$$uisDebounce', ['$timeout', function($timeout) {
  175. return function(callback, debounceTime) {
  176. var timeoutPromise;
  177. return function() {
  178. var self = this;
  179. var args = Array.prototype.slice.call(arguments);
  180. if (timeoutPromise) {
  181. $timeout.cancel(timeoutPromise);
  182. }
  183. timeoutPromise = $timeout(function() {
  184. callback.apply(self, args);
  185. }, debounceTime);
  186. };
  187. };
  188. }]);
  189. uis.directive('uiSelectChoices',
  190. ['uiSelectConfig', 'uisRepeatParser', 'uiSelectMinErr', '$compile', '$window',
  191. function(uiSelectConfig, RepeatParser, uiSelectMinErr, $compile, $window) {
  192. return {
  193. restrict: 'EA',
  194. require: '^uiSelect',
  195. replace: true,
  196. transclude: true,
  197. templateUrl: function(tElement) {
  198. // Needed so the uiSelect can detect the transcluded content
  199. tElement.addClass('ui-select-choices');
  200. // Gets theme attribute from parent (ui-select)
  201. var theme = tElement.parent().attr('theme') || uiSelectConfig.theme;
  202. return theme + '/choices.tpl.html';
  203. },
  204. compile: function(tElement, tAttrs) {
  205. if (!tAttrs.repeat) throw uiSelectMinErr('repeat', "Expected 'repeat' expression.");
  206. // var repeat = RepeatParser.parse(attrs.repeat);
  207. var groupByExp = tAttrs.groupBy;
  208. var groupFilterExp = tAttrs.groupFilter;
  209. if (groupByExp) {
  210. var groups = tElement.querySelectorAll('.ui-select-choices-group');
  211. if (groups.length !== 1) throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-group but got '{0}'.", groups.length);
  212. groups.attr('ng-repeat', RepeatParser.getGroupNgRepeatExpression());
  213. }
  214. var parserResult = RepeatParser.parse(tAttrs.repeat);
  215. var choices = tElement.querySelectorAll('.ui-select-choices-row');
  216. if (choices.length !== 1) {
  217. throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row but got '{0}'.", choices.length);
  218. }
  219. choices.attr('ng-repeat', parserResult.repeatExpression(groupByExp))
  220. .attr('ng-if', '$select.open'); //Prevent unnecessary watches when dropdown is closed
  221. var rowsInner = tElement.querySelectorAll('.ui-select-choices-row-inner');
  222. if (rowsInner.length !== 1) {
  223. throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row-inner but got '{0}'.", rowsInner.length);
  224. }
  225. rowsInner.attr('uis-transclude-append', ''); //Adding uisTranscludeAppend directive to row element after choices element has ngRepeat
  226. // If IE8 then need to target rowsInner to apply the ng-click attr as choices will not capture the event.
  227. var clickTarget = $window.document.addEventListener ? choices : rowsInner;
  228. clickTarget.attr('ng-click', '$select.select(' + parserResult.itemName + ',$select.skipFocusser,$event)');
  229. return function link(scope, element, attrs, $select) {
  230. $select.parseRepeatAttr(attrs.repeat, groupByExp, groupFilterExp); //Result ready at $select.parserResult
  231. $select.disableChoiceExpression = attrs.uiDisableChoice;
  232. $select.onHighlightCallback = attrs.onHighlight;
  233. $select.minimumInputLength = parseInt(attrs.minimumInputLength) || 0;
  234. $select.dropdownPosition = attrs.position ? attrs.position.toLowerCase() : uiSelectConfig.dropdownPosition;
  235. scope.$watch('$select.search', function(newValue) {
  236. if(newValue && !$select.open && $select.multiple) $select.activate(false, true);
  237. $select.activeIndex = $select.tagging.isActivated ? -1 : 0;
  238. if (!attrs.minimumInputLength || $select.search.length >= attrs.minimumInputLength) {
  239. $select.refresh(attrs.refresh);
  240. } else {
  241. $select.items = [];
  242. }
  243. });
  244. attrs.$observe('refreshDelay', function() {
  245. // $eval() is needed otherwise we get a string instead of a number
  246. var refreshDelay = scope.$eval(attrs.refreshDelay);
  247. $select.refreshDelay = refreshDelay !== undefined ? refreshDelay : uiSelectConfig.refreshDelay;
  248. });
  249. scope.$watch('$select.open', function(open) {
  250. if (open) {
  251. tElement.attr('role', 'listbox');
  252. $select.refresh(attrs.refresh);
  253. } else {
  254. element.removeAttr('role');
  255. }
  256. });
  257. };
  258. }
  259. };
  260. }]);
  261. /**
  262. * Contains ui-select "intelligence".
  263. *
  264. * The goal is to limit dependency on the DOM whenever possible and
  265. * put as much logic in the controller (instead of the link functions) as possible so it can be easily tested.
  266. */
  267. uis.controller('uiSelectCtrl',
  268. ['$scope', '$element', '$timeout', '$filter', '$$uisDebounce', 'uisRepeatParser', 'uiSelectMinErr', 'uiSelectConfig', '$parse', '$injector', '$window',
  269. function($scope, $element, $timeout, $filter, $$uisDebounce, RepeatParser, uiSelectMinErr, uiSelectConfig, $parse, $injector, $window) {
  270. var ctrl = this;
  271. var EMPTY_SEARCH = '';
  272. ctrl.placeholder = uiSelectConfig.placeholder;
  273. ctrl.searchEnabled = uiSelectConfig.searchEnabled;
  274. ctrl.sortable = uiSelectConfig.sortable;
  275. ctrl.refreshDelay = uiSelectConfig.refreshDelay;
  276. ctrl.paste = uiSelectConfig.paste;
  277. ctrl.resetSearchInput = uiSelectConfig.resetSearchInput;
  278. ctrl.refreshing = false;
  279. ctrl.spinnerEnabled = uiSelectConfig.spinnerEnabled;
  280. ctrl.spinnerClass = uiSelectConfig.spinnerClass;
  281. ctrl.removeSelected = uiSelectConfig.removeSelected; //If selected item(s) should be removed from dropdown list
  282. ctrl.closeOnSelect = true; //Initialized inside uiSelect directive link function
  283. ctrl.skipFocusser = false; //Set to true to avoid returning focus to ctrl when item is selected
  284. ctrl.search = EMPTY_SEARCH;
  285. ctrl.activeIndex = 0; //Dropdown of choices
  286. ctrl.items = []; //All available choices
  287. ctrl.open = false;
  288. ctrl.focus = false;
  289. ctrl.disabled = false;
  290. ctrl.selected = undefined;
  291. ctrl.dropdownPosition = 'auto';
  292. ctrl.focusser = undefined; //Reference to input element used to handle focus events
  293. ctrl.multiple = undefined; // Initialized inside uiSelect directive link function
  294. ctrl.disableChoiceExpression = undefined; // Initialized inside uiSelectChoices directive link function
  295. ctrl.tagging = {isActivated: false, fct: undefined};
  296. ctrl.taggingTokens = {isActivated: false, tokens: undefined};
  297. ctrl.lockChoiceExpression = undefined; // Initialized inside uiSelectMatch directive link function
  298. ctrl.clickTriggeredSelect = false;
  299. ctrl.$filter = $filter;
  300. ctrl.$element = $element;
  301. // Use $injector to check for $animate and store a reference to it
  302. ctrl.$animate = (function () {
  303. try {
  304. return $injector.get('$animate');
  305. } catch (err) {
  306. // $animate does not exist
  307. return null;
  308. }
  309. })();
  310. ctrl.searchInput = $element.querySelectorAll('input.ui-select-search');
  311. if (ctrl.searchInput.length !== 1) {
  312. throw uiSelectMinErr('searchInput', "Expected 1 input.ui-select-search but got '{0}'.", ctrl.searchInput.length);
  313. }
  314. ctrl.isEmpty = function() {
  315. return isNil(ctrl.selected) || ctrl.selected === '' || (ctrl.multiple && ctrl.selected.length === 0);
  316. };
  317. function _findIndex(collection, predicate, thisArg){
  318. if (collection.findIndex){
  319. return collection.findIndex(predicate, thisArg);
  320. } else {
  321. var list = Object(collection);
  322. var length = list.length >>> 0;
  323. var value;
  324. for (var i = 0; i < length; i++) {
  325. value = list[i];
  326. if (predicate.call(thisArg, value, i, list)) {
  327. return i;
  328. }
  329. }
  330. return -1;
  331. }
  332. }
  333. // Most of the time the user does not want to empty the search input when in typeahead mode
  334. function _resetSearchInput() {
  335. if (ctrl.resetSearchInput) {
  336. ctrl.search = EMPTY_SEARCH;
  337. //reset activeIndex
  338. if (ctrl.selected && ctrl.items.length && !ctrl.multiple) {
  339. ctrl.activeIndex = _findIndex(ctrl.items, function(item){
  340. return angular.equals(this, item);
  341. }, ctrl.selected);
  342. }
  343. }
  344. }
  345. function _groupsFilter(groups, groupNames) {
  346. var i, j, result = [];
  347. for(i = 0; i < groupNames.length ;i++){
  348. for(j = 0; j < groups.length ;j++){
  349. if(groups[j].name == [groupNames[i]]){
  350. result.push(groups[j]);
  351. }
  352. }
  353. }
  354. return result;
  355. }
  356. // When the user clicks on ui-select, displays the dropdown list
  357. ctrl.activate = function(initSearchValue, avoidReset) {
  358. if (!ctrl.disabled && !ctrl.open) {
  359. if(!avoidReset) _resetSearchInput();
  360. $scope.$broadcast('uis:activate');
  361. ctrl.open = true;
  362. ctrl.activeIndex = ctrl.activeIndex >= ctrl.items.length ? 0 : ctrl.activeIndex;
  363. // ensure that the index is set to zero for tagging variants
  364. // that where first option is auto-selected
  365. if ( ctrl.activeIndex === -1 && ctrl.taggingLabel !== false ) {
  366. ctrl.activeIndex = 0;
  367. }
  368. var container = $element.querySelectorAll('.ui-select-choices-content');
  369. var searchInput = $element.querySelectorAll('.ui-select-search');
  370. if (ctrl.$animate && ctrl.$animate.on && ctrl.$animate.enabled(container[0])) {
  371. var animateHandler = function(elem, phase) {
  372. if (phase === 'start' && ctrl.items.length === 0) {
  373. // Only focus input after the animation has finished
  374. ctrl.$animate.off('removeClass', searchInput[0], animateHandler);
  375. $timeout(function () {
  376. ctrl.focusSearchInput(initSearchValue);
  377. });
  378. } else if (phase === 'close') {
  379. // Only focus input after the animation has finished
  380. ctrl.$animate.off('enter', container[0], animateHandler);
  381. $timeout(function () {
  382. ctrl.focusSearchInput(initSearchValue);
  383. });
  384. }
  385. };
  386. if (ctrl.items.length > 0) {
  387. ctrl.$animate.on('enter', container[0], animateHandler);
  388. } else {
  389. ctrl.$animate.on('removeClass', searchInput[0], animateHandler);
  390. }
  391. } else {
  392. $timeout(function () {
  393. ctrl.focusSearchInput(initSearchValue);
  394. if(!ctrl.tagging.isActivated && ctrl.items.length > 1) {
  395. _ensureHighlightVisible();
  396. }
  397. });
  398. }
  399. }
  400. else if (ctrl.open && !ctrl.searchEnabled) {
  401. // Close the selection if we don't have search enabled, and we click on the select again
  402. ctrl.close();
  403. }
  404. };
  405. ctrl.focusSearchInput = function (initSearchValue) {
  406. ctrl.search = initSearchValue || ctrl.search;
  407. ctrl.searchInput[0].focus();
  408. };
  409. ctrl.findGroupByName = function(name) {
  410. return ctrl.groups && ctrl.groups.filter(function(group) {
  411. return group.name === name;
  412. })[0];
  413. };
  414. ctrl.parseRepeatAttr = function(repeatAttr, groupByExp, groupFilterExp) {
  415. function updateGroups(items) {
  416. var groupFn = $scope.$eval(groupByExp);
  417. ctrl.groups = [];
  418. angular.forEach(items, function(item) {
  419. var groupName = angular.isFunction(groupFn) ? groupFn(item) : item[groupFn];
  420. var group = ctrl.findGroupByName(groupName);
  421. if(group) {
  422. group.items.push(item);
  423. }
  424. else {
  425. ctrl.groups.push({name: groupName, items: [item]});
  426. }
  427. });
  428. if(groupFilterExp){
  429. var groupFilterFn = $scope.$eval(groupFilterExp);
  430. if( angular.isFunction(groupFilterFn)){
  431. ctrl.groups = groupFilterFn(ctrl.groups);
  432. } else if(angular.isArray(groupFilterFn)){
  433. ctrl.groups = _groupsFilter(ctrl.groups, groupFilterFn);
  434. }
  435. }
  436. ctrl.items = [];
  437. ctrl.groups.forEach(function(group) {
  438. ctrl.items = ctrl.items.concat(group.items);
  439. });
  440. }
  441. function setPlainItems(items) {
  442. ctrl.items = items || [];
  443. }
  444. ctrl.setItemsFn = groupByExp ? updateGroups : setPlainItems;
  445. ctrl.parserResult = RepeatParser.parse(repeatAttr);
  446. ctrl.isGrouped = !!groupByExp;
  447. ctrl.itemProperty = ctrl.parserResult.itemName;
  448. //If collection is an Object, convert it to Array
  449. var originalSource = ctrl.parserResult.source;
  450. //When an object is used as source, we better create an array and use it as 'source'
  451. var createArrayFromObject = function(){
  452. var origSrc = originalSource($scope);
  453. $scope.$uisSource = Object.keys(origSrc).map(function(v){
  454. var result = {};
  455. result[ctrl.parserResult.keyName] = v;
  456. result.value = origSrc[v];
  457. return result;
  458. });
  459. };
  460. if (ctrl.parserResult.keyName){ // Check for (key,value) syntax
  461. createArrayFromObject();
  462. ctrl.parserResult.source = $parse('$uisSource' + ctrl.parserResult.filters);
  463. $scope.$watch(originalSource, function(newVal, oldVal){
  464. if (newVal !== oldVal) createArrayFromObject();
  465. }, true);
  466. }
  467. ctrl.refreshItems = function (data){
  468. data = data || ctrl.parserResult.source($scope);
  469. var selectedItems = ctrl.selected;
  470. //TODO should implement for single mode removeSelected
  471. if (ctrl.isEmpty() || (angular.isArray(selectedItems) && !selectedItems.length) || !ctrl.multiple || !ctrl.removeSelected) {
  472. ctrl.setItemsFn(data);
  473. }else{
  474. if ( data !== undefined && data !== null ) {
  475. var filteredItems = data.filter(function(i) {
  476. return angular.isArray(selectedItems) ? selectedItems.every(function(selectedItem) {
  477. return !angular.equals(i, selectedItem);
  478. }) : !angular.equals(i, selectedItems);
  479. });
  480. ctrl.setItemsFn(filteredItems);
  481. }
  482. }
  483. if (ctrl.dropdownPosition === 'auto' || ctrl.dropdownPosition === 'up'){
  484. $scope.calculateDropdownPos();
  485. }
  486. $scope.$broadcast('uis:refresh');
  487. };
  488. // See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L259
  489. $scope.$watchCollection(ctrl.parserResult.source, function(items) {
  490. if (items === undefined || items === null) {
  491. // If the user specifies undefined or null => reset the collection
  492. // Special case: items can be undefined if the user did not initialized the collection on the scope
  493. // i.e $scope.addresses = [] is missing
  494. ctrl.items = [];
  495. } else {
  496. if (!angular.isArray(items)) {
  497. throw uiSelectMinErr('items', "Expected an array but got '{0}'.", items);
  498. } else {
  499. //Remove already selected items (ex: while searching)
  500. //TODO Should add a test
  501. ctrl.refreshItems(items);
  502. //update the view value with fresh data from items, if there is a valid model value
  503. if(angular.isDefined(ctrl.ngModel.$modelValue)) {
  504. ctrl.ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters
  505. }
  506. }
  507. }
  508. });
  509. };
  510. var _refreshDelayPromise;
  511. /**
  512. * Typeahead mode: lets the user refresh the collection using his own function.
  513. *
  514. * See Expose $select.search for external / remote filtering https://github.com/angular-ui/ui-select/pull/31
  515. */
  516. ctrl.refresh = function(refreshAttr) {
  517. if (refreshAttr !== undefined) {
  518. // Debounce
  519. // See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L155
  520. // FYI AngularStrap typeahead does not have debouncing: https://github.com/mgcrea/angular-strap/blob/v2.0.0-rc.4/src/typeahead/typeahead.js#L177
  521. if (_refreshDelayPromise) {
  522. $timeout.cancel(_refreshDelayPromise);
  523. }
  524. _refreshDelayPromise = $timeout(function() {
  525. if ($scope.$select.search.length >= $scope.$select.minimumInputLength) {
  526. var refreshPromise = $scope.$eval(refreshAttr);
  527. if (refreshPromise && angular.isFunction(refreshPromise.then) && !ctrl.refreshing) {
  528. ctrl.refreshing = true;
  529. refreshPromise.finally(function() {
  530. ctrl.refreshing = false;
  531. });
  532. }
  533. }
  534. }, ctrl.refreshDelay);
  535. }
  536. };
  537. ctrl.isActive = function(itemScope) {
  538. if ( !ctrl.open ) {
  539. return false;
  540. }
  541. var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]);
  542. var isActive = itemIndex == ctrl.activeIndex;
  543. if ( !isActive || itemIndex < 0 ) {
  544. return false;
  545. }
  546. if (isActive && !angular.isUndefined(ctrl.onHighlightCallback)) {
  547. itemScope.$eval(ctrl.onHighlightCallback);
  548. }
  549. return isActive;
  550. };
  551. var _isItemSelected = function (item) {
  552. return (ctrl.selected && angular.isArray(ctrl.selected) &&
  553. ctrl.selected.filter(function (selection) { return angular.equals(selection, item); }).length > 0);
  554. };
  555. var disabledItems = [];
  556. function _updateItemDisabled(item, isDisabled) {
  557. var disabledItemIndex = disabledItems.indexOf(item);
  558. if (isDisabled && disabledItemIndex === -1) {
  559. disabledItems.push(item);
  560. }
  561. if (!isDisabled && disabledItemIndex > -1) {
  562. disabledItems.splice(disabledItemIndex, 1);
  563. }
  564. }
  565. function _isItemDisabled(item) {
  566. return disabledItems.indexOf(item) > -1;
  567. }
  568. ctrl.isDisabled = function(itemScope) {
  569. if (!ctrl.open) return;
  570. var item = itemScope[ctrl.itemProperty];
  571. var itemIndex = ctrl.items.indexOf(item);
  572. var isDisabled = false;
  573. if (itemIndex >= 0 && (angular.isDefined(ctrl.disableChoiceExpression) || ctrl.multiple)) {
  574. if (item.isTag) return false;
  575. if (ctrl.multiple) {
  576. isDisabled = _isItemSelected(item);
  577. }
  578. if (!isDisabled && angular.isDefined(ctrl.disableChoiceExpression)) {
  579. isDisabled = !!(itemScope.$eval(ctrl.disableChoiceExpression));
  580. }
  581. _updateItemDisabled(item, isDisabled);
  582. }
  583. return isDisabled;
  584. };
  585. // When the user selects an item with ENTER or clicks the dropdown
  586. ctrl.select = function(item, skipFocusser, $event) {
  587. if (isNil(item) || !_isItemDisabled(item)) {
  588. if ( ! ctrl.items && ! ctrl.search && ! ctrl.tagging.isActivated) return;
  589. if (!item || !_isItemDisabled(item)) {
  590. // if click is made on existing item, prevent from tagging, ctrl.search does not matter
  591. ctrl.clickTriggeredSelect = false;
  592. if($event && ($event.type === 'click' || $event.type === 'touchend') && item)
  593. ctrl.clickTriggeredSelect = true;
  594. if(ctrl.tagging.isActivated && ctrl.clickTriggeredSelect === false) {
  595. // if taggingLabel is disabled and item is undefined we pull from ctrl.search
  596. if ( ctrl.taggingLabel === false ) {
  597. if ( ctrl.activeIndex < 0 ) {
  598. if (item === undefined) {
  599. item = ctrl.tagging.fct !== undefined ? ctrl.tagging.fct(ctrl.search) : ctrl.search;
  600. }
  601. if (!item || angular.equals( ctrl.items[0], item ) ) {
  602. return;
  603. }
  604. } else {
  605. // keyboard nav happened first, user selected from dropdown
  606. item = ctrl.items[ctrl.activeIndex];
  607. }
  608. } else {
  609. // tagging always operates at index zero, taggingLabel === false pushes
  610. // the ctrl.search value without having it injected
  611. if ( ctrl.activeIndex === 0 ) {
  612. // ctrl.tagging pushes items to ctrl.items, so we only have empty val
  613. // for `item` if it is a detected duplicate
  614. if ( item === undefined ) return;
  615. // create new item on the fly if we don't already have one;
  616. // use tagging function if we have one
  617. if ( ctrl.tagging.fct !== undefined && typeof item === 'string' ) {
  618. item = ctrl.tagging.fct(item);
  619. if (!item) return;
  620. // if item type is 'string', apply the tagging label
  621. } else if ( typeof item === 'string' ) {
  622. // trim the trailing space
  623. item = item.replace(ctrl.taggingLabel,'').trim();
  624. }
  625. }
  626. }
  627. // search ctrl.selected for dupes potentially caused by tagging and return early if found
  628. if (_isItemSelected(item)) {
  629. ctrl.close(skipFocusser);
  630. return;
  631. }
  632. }
  633. _resetSearchInput();
  634. $scope.$broadcast('uis:select', item);
  635. if (ctrl.closeOnSelect) {
  636. ctrl.close(skipFocusser);
  637. }
  638. }
  639. }
  640. };
  641. // Closes the dropdown
  642. ctrl.close = function(skipFocusser) {
  643. if (!ctrl.open) return;
  644. if (ctrl.ngModel && ctrl.ngModel.$setTouched) ctrl.ngModel.$setTouched();
  645. ctrl.open = false;
  646. _resetSearchInput();
  647. $scope.$broadcast('uis:close', skipFocusser);
  648. };
  649. ctrl.setFocus = function(){
  650. if (!ctrl.focus) ctrl.focusInput[0].focus();
  651. };
  652. ctrl.clear = function($event) {
  653. ctrl.select(null);
  654. $event.stopPropagation();
  655. $timeout(function() {
  656. ctrl.focusser[0].focus();
  657. }, 0, false);
  658. };
  659. // Toggle dropdown
  660. ctrl.toggle = function(e) {
  661. if (ctrl.open) {
  662. ctrl.close();
  663. e.preventDefault();
  664. e.stopPropagation();
  665. } else {
  666. ctrl.activate();
  667. }
  668. };
  669. // Set default function for locked choices - avoids unnecessary
  670. // logic if functionality is not being used
  671. ctrl.isLocked = function () {
  672. return false;
  673. };
  674. $scope.$watch(function () {
  675. return angular.isDefined(ctrl.lockChoiceExpression) && ctrl.lockChoiceExpression !== "";
  676. }, _initaliseLockedChoices);
  677. function _initaliseLockedChoices(doInitalise) {
  678. if(!doInitalise) return;
  679. var lockedItems = [];
  680. function _updateItemLocked(item, isLocked) {
  681. var lockedItemIndex = lockedItems.indexOf(item);
  682. if (isLocked && lockedItemIndex === -1) {
  683. lockedItems.push(item);
  684. }
  685. if (!isLocked && lockedItemIndex > -1) {
  686. lockedItems.splice(lockedItemIndex, 1);
  687. }
  688. }
  689. function _isItemlocked(item) {
  690. return lockedItems.indexOf(item) > -1;
  691. }
  692. ctrl.isLocked = function (itemScope, itemIndex) {
  693. var isLocked = false,
  694. item = ctrl.selected[itemIndex];
  695. if(item) {
  696. if (itemScope) {
  697. isLocked = !!(itemScope.$eval(ctrl.lockChoiceExpression));
  698. _updateItemLocked(item, isLocked);
  699. } else {
  700. isLocked = _isItemlocked(item);
  701. }
  702. }
  703. return isLocked;
  704. };
  705. }
  706. var sizeWatch = null;
  707. var updaterScheduled = false;
  708. ctrl.sizeSearchInput = function() {
  709. var input = ctrl.searchInput[0],
  710. container = ctrl.$element[0],
  711. calculateContainerWidth = function() {
  712. // Return the container width only if the search input is visible
  713. return container.clientWidth * !!input.offsetParent;
  714. },
  715. updateIfVisible = function(containerWidth) {
  716. if (containerWidth === 0) {
  717. return false;
  718. }
  719. var inputWidth = containerWidth - input.offsetLeft;
  720. if (inputWidth < 50) inputWidth = containerWidth;
  721. ctrl.searchInput.css('width', inputWidth+'px');
  722. return true;
  723. };
  724. ctrl.searchInput.css('width', '10px');
  725. $timeout(function() { //Give tags time to render correctly
  726. if (sizeWatch === null && !updateIfVisible(calculateContainerWidth())) {
  727. sizeWatch = $scope.$watch(function() {
  728. if (!updaterScheduled) {
  729. updaterScheduled = true;
  730. $scope.$$postDigest(function() {
  731. updaterScheduled = false;
  732. if (updateIfVisible(calculateContainerWidth())) {
  733. sizeWatch();
  734. sizeWatch = null;
  735. }
  736. });
  737. }
  738. }, angular.noop);
  739. }
  740. });
  741. };
  742. function _handleDropDownSelection(key) {
  743. var processed = true;
  744. switch (key) {
  745. case KEY.DOWN:
  746. if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode
  747. else if (ctrl.activeIndex < ctrl.items.length - 1) {
  748. var idx = ++ctrl.activeIndex;
  749. while(_isItemDisabled(ctrl.items[idx]) && idx < ctrl.items.length) {
  750. ctrl.activeIndex = ++idx;
  751. }
  752. }
  753. break;
  754. case KEY.UP:
  755. var minActiveIndex = (ctrl.search.length === 0 && ctrl.tagging.isActivated) ? -1 : 0;
  756. if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode
  757. else if (ctrl.activeIndex > minActiveIndex) {
  758. var idxmin = --ctrl.activeIndex;
  759. while(_isItemDisabled(ctrl.items[idxmin]) && idxmin > minActiveIndex) {
  760. ctrl.activeIndex = --idxmin;
  761. }
  762. }
  763. break;
  764. case KEY.TAB:
  765. if (!ctrl.multiple || ctrl.open) ctrl.select(ctrl.items[ctrl.activeIndex], true);
  766. break;
  767. case KEY.ENTER:
  768. if(ctrl.open && (ctrl.tagging.isActivated || ctrl.activeIndex >= 0)){
  769. ctrl.select(ctrl.items[ctrl.activeIndex], ctrl.skipFocusser); // Make sure at least one dropdown item is highlighted before adding if not in tagging mode
  770. } else {
  771. ctrl.activate(false, true); //In case its the search input in 'multiple' mode
  772. }
  773. break;
  774. case KEY.ESC:
  775. ctrl.close();
  776. break;
  777. default:
  778. processed = false;
  779. }
  780. return processed;
  781. }
  782. // Bind to keyboard shortcuts
  783. ctrl.searchInput.on('keydown', function(e) {
  784. var key = e.which;
  785. if (~[KEY.ENTER,KEY.ESC].indexOf(key)){
  786. e.preventDefault();
  787. e.stopPropagation();
  788. }
  789. $scope.$apply(function() {
  790. var tagged = false;
  791. if (ctrl.items.length > 0 || ctrl.tagging.isActivated) {
  792. if(!_handleDropDownSelection(key) && !ctrl.searchEnabled) {
  793. e.preventDefault();
  794. e.stopPropagation();
  795. }
  796. if ( ctrl.taggingTokens.isActivated ) {
  797. for (var i = 0; i < ctrl.taggingTokens.tokens.length; i++) {
  798. if ( ctrl.taggingTokens.tokens[i] === KEY.MAP[e.keyCode] ) {
  799. // make sure there is a new value to push via tagging
  800. if ( ctrl.search.length > 0 ) {
  801. tagged = true;
  802. }
  803. }
  804. }
  805. if ( tagged ) {
  806. $timeout(function() {
  807. ctrl.searchInput.triggerHandler('tagged');
  808. var newItem = ctrl.search.replace(KEY.MAP[e.keyCode],'').trim();
  809. if ( ctrl.tagging.fct ) {
  810. newItem = ctrl.tagging.fct( newItem );
  811. }
  812. if (newItem) ctrl.select(newItem, true);
  813. });
  814. }
  815. }
  816. }
  817. });
  818. if(KEY.isVerticalMovement(key) && ctrl.items.length > 0){
  819. _ensureHighlightVisible();
  820. }
  821. if (key === KEY.ENTER || key === KEY.ESC) {
  822. e.preventDefault();
  823. e.stopPropagation();
  824. }
  825. });
  826. ctrl.searchInput.on('paste', function (e) {
  827. var data;
  828. if (window.clipboardData && window.clipboardData.getData) { // IE
  829. data = window.clipboardData.getData('Text');
  830. } else {
  831. data = (e.originalEvent || e).clipboardData.getData('text/plain');
  832. }
  833. // Prepend the current input field text to the paste buffer.
  834. data = ctrl.search + data;
  835. if (data && data.length > 0) {
  836. // If tagging try to split by tokens and add items
  837. if (ctrl.taggingTokens.isActivated) {
  838. var items = [];
  839. for (var i = 0; i < ctrl.taggingTokens.tokens.length; i++) { // split by first token that is contained in data
  840. var separator = KEY.toSeparator(ctrl.taggingTokens.tokens[i]) || ctrl.taggingTokens.tokens[i];
  841. if (data.indexOf(separator) > -1) {
  842. items = data.split(separator);
  843. break; // only split by one token
  844. }
  845. }
  846. if (items.length === 0) {
  847. items = [data];
  848. }
  849. var oldsearch = ctrl.search;
  850. angular.forEach(items, function (item) {
  851. var newItem = ctrl.tagging.fct ? ctrl.tagging.fct(item) : item;
  852. if (newItem) {
  853. ctrl.select(newItem, true);
  854. }
  855. });
  856. ctrl.search = oldsearch || EMPTY_SEARCH;
  857. e.preventDefault();
  858. e.stopPropagation();
  859. } else if (ctrl.paste) {
  860. ctrl.paste(data);
  861. ctrl.search = EMPTY_SEARCH;
  862. e.preventDefault();
  863. e.stopPropagation();
  864. }
  865. }
  866. });
  867. ctrl.searchInput.on('tagged', function() {
  868. $timeout(function() {
  869. _resetSearchInput();
  870. });
  871. });
  872. // See https://github.com/ivaynberg/select2/blob/3.4.6/select2.js#L1431
  873. function _ensureHighlightVisible() {
  874. var container = $element.querySelectorAll('.ui-select-choices-content');
  875. var choices = container.querySelectorAll('.ui-select-choices-row');
  876. if (choices.length < 1) {
  877. throw uiSelectMinErr('choices', "Expected multiple .ui-select-choices-row but got '{0}'.", choices.length);
  878. }
  879. if (ctrl.activeIndex < 0) {
  880. return;
  881. }
  882. var highlighted = choices[ctrl.activeIndex];
  883. var posY = highlighted.offsetTop + highlighted.clientHeight - container[0].scrollTop;
  884. var height = container[0].offsetHeight;
  885. if (posY > height) {
  886. container[0].scrollTop += posY - height;
  887. } else if (posY < highlighted.clientHeight) {
  888. if (ctrl.isGrouped && ctrl.activeIndex === 0)
  889. container[0].scrollTop = 0; //To make group header visible when going all the way up
  890. else
  891. container[0].scrollTop -= highlighted.clientHeight - posY;
  892. }
  893. }
  894. var onResize = $$uisDebounce(function() {
  895. ctrl.sizeSearchInput();
  896. }, 50);
  897. angular.element($window).bind('resize', onResize);
  898. $scope.$on('$destroy', function() {
  899. ctrl.searchInput.off('keyup keydown tagged blur paste');
  900. angular.element($window).off('resize', onResize);
  901. });
  902. $scope.$watch('$select.activeIndex', function(activeIndex) {
  903. if (activeIndex)
  904. $element.find('input').attr(
  905. 'aria-activedescendant',
  906. 'ui-select-choices-row-' + ctrl.generatedId + '-' + activeIndex);
  907. });
  908. $scope.$watch('$select.open', function(open) {
  909. if (!open)
  910. $element.find('input').removeAttr('aria-activedescendant');
  911. });
  912. }]);
  913. uis.directive('uiSelect',
  914. ['$document', 'uiSelectConfig', 'uiSelectMinErr', 'uisOffset', '$compile', '$parse', '$timeout',
  915. function($document, uiSelectConfig, uiSelectMinErr, uisOffset, $compile, $parse, $timeout) {
  916. return {
  917. restrict: 'EA',
  918. templateUrl: function(tElement, tAttrs) {
  919. var theme = tAttrs.theme || uiSelectConfig.theme;
  920. return theme + (angular.isDefined(tAttrs.multiple) ? '/select-multiple.tpl.html' : '/select.tpl.html');
  921. },
  922. replace: true,
  923. transclude: true,
  924. require: ['uiSelect', '^ngModel'],
  925. scope: true,
  926. controller: 'uiSelectCtrl',
  927. controllerAs: '$select',
  928. compile: function(tElement, tAttrs) {
  929. // Allow setting ngClass on uiSelect
  930. var match = /{(.*)}\s*{(.*)}/.exec(tAttrs.ngClass);
  931. if(match) {
  932. var combined = '{'+ match[1] +', '+ match[2] +'}';
  933. tAttrs.ngClass = combined;
  934. tElement.attr('ng-class', combined);
  935. }
  936. //Multiple or Single depending if multiple attribute presence
  937. if (angular.isDefined(tAttrs.multiple))
  938. tElement.append('<ui-select-multiple/>').removeAttr('multiple');
  939. else
  940. tElement.append('<ui-select-single/>');
  941. if (tAttrs.inputId)
  942. tElement.querySelectorAll('input.ui-select-search')[0].id = tAttrs.inputId;
  943. return function(scope, element, attrs, ctrls, transcludeFn) {
  944. var $select = ctrls[0];
  945. var ngModel = ctrls[1];
  946. $select.generatedId = uiSelectConfig.generateId();
  947. $select.baseTitle = attrs.title || 'Select box';
  948. $select.focusserTitle = $select.baseTitle + ' focus';
  949. $select.focusserId = 'focusser-' + $select.generatedId;
  950. $select.closeOnSelect = function() {
  951. if (angular.isDefined(attrs.closeOnSelect)) {
  952. return $parse(attrs.closeOnSelect)();
  953. } else {
  954. return uiSelectConfig.closeOnSelect;
  955. }
  956. }();
  957. scope.$watch('skipFocusser', function() {
  958. var skipFocusser = scope.$eval(attrs.skipFocusser);
  959. $select.skipFocusser = skipFocusser !== undefined ? skipFocusser : uiSelectConfig.skipFocusser;
  960. });
  961. $select.onSelectCallback = $parse(attrs.onSelect);
  962. $select.onRemoveCallback = $parse(attrs.onRemove);
  963. //Set reference to ngModel from uiSelectCtrl
  964. $select.ngModel = ngModel;
  965. $select.choiceGrouped = function(group){
  966. return $select.isGrouped && group && group.name;
  967. };
  968. if(attrs.tabindex){
  969. attrs.$observe('tabindex', function(value) {
  970. $select.focusInput.attr('tabindex', value);
  971. element.removeAttr('tabindex');
  972. });
  973. }
  974. scope.$watch(function () { return scope.$eval(attrs.searchEnabled); }, function(newVal) {
  975. $select.searchEnabled = newVal !== undefined ? newVal : uiSelectConfig.searchEnabled;
  976. });
  977. scope.$watch('sortable', function() {
  978. var sortable = scope.$eval(attrs.sortable);
  979. $select.sortable = sortable !== undefined ? sortable : uiSelectConfig.sortable;
  980. });
  981. attrs.$observe('backspaceReset', function() {
  982. // $eval() is needed otherwise we get a string instead of a boolean
  983. var backspaceReset = scope.$eval(attrs.backspaceReset);
  984. $select.backspaceReset = backspaceReset !== undefined ? backspaceReset : true;
  985. });
  986. attrs.$observe('limit', function() {
  987. //Limit the number of selections allowed
  988. $select.limit = (angular.isDefined(attrs.limit)) ? parseInt(attrs.limit, 10) : undefined;
  989. });
  990. scope.$watch('removeSelected', function() {
  991. var removeSelected = scope.$eval(attrs.removeSelected);
  992. $select.removeSelected = removeSelected !== undefined ? removeSelected : uiSelectConfig.removeSelected;
  993. });
  994. attrs.$observe('disabled', function() {
  995. // No need to use $eval() (thanks to ng-disabled) since we already get a boolean instead of a string
  996. $select.disabled = attrs.disabled !== undefined ? attrs.disabled : false;
  997. });
  998. attrs.$observe('resetSearchInput', function() {
  999. // $eval() is needed otherwise we get a string instead of a boolean
  1000. var resetSearchInput = scope.$eval(attrs.resetSearchInput);
  1001. $select.resetSearchInput = resetSearchInput !== undefined ? resetSearchInput : true;
  1002. });
  1003. attrs.$observe('paste', function() {
  1004. $select.paste = scope.$eval(attrs.paste);
  1005. });
  1006. attrs.$observe('tagging', function() {
  1007. if(attrs.tagging !== undefined)
  1008. {
  1009. // $eval() is needed otherwise we get a string instead of a boolean
  1010. var taggingEval = scope.$eval(attrs.tagging);
  1011. $select.tagging = {isActivated: true, fct: taggingEval !== true ? taggingEval : undefined};
  1012. }
  1013. else
  1014. {
  1015. $select.tagging = {isActivated: false, fct: undefined};
  1016. }
  1017. });
  1018. attrs.$observe('taggingLabel', function() {
  1019. if(attrs.tagging !== undefined )
  1020. {
  1021. // check eval for FALSE, in this case, we disable the labels
  1022. // associated with tagging
  1023. if ( attrs.taggingLabel === 'false' ) {
  1024. $select.taggingLabel = false;
  1025. }
  1026. else
  1027. {
  1028. $select.taggingLabel = attrs.taggingLabel !== undefined ? attrs.taggingLabel : '(new)';
  1029. }
  1030. }
  1031. });
  1032. attrs.$observe('taggingTokens', function() {
  1033. if (attrs.tagging !== undefined) {
  1034. var tokens = attrs.taggingTokens !== undefined ? attrs.taggingTokens.split('|') : [',','ENTER'];
  1035. $select.taggingTokens = {isActivated: true, tokens: tokens };
  1036. }
  1037. });
  1038. attrs.$observe('spinnerEnabled', function() {
  1039. // $eval() is needed otherwise we get a string instead of a boolean
  1040. var spinnerEnabled = scope.$eval(attrs.spinnerEnabled);
  1041. $select.spinnerEnabled = spinnerEnabled !== undefined ? spinnerEnabled : uiSelectConfig.spinnerEnabled;
  1042. });
  1043. attrs.$observe('spinnerClass', function() {
  1044. var spinnerClass = attrs.spinnerClass;
  1045. $select.spinnerClass = spinnerClass !== undefined ? attrs.spinnerClass : uiSelectConfig.spinnerClass;
  1046. });
  1047. //Automatically gets focus when loaded
  1048. if (angular.isDefined(attrs.autofocus)){
  1049. $timeout(function(){
  1050. $select.setFocus();
  1051. });
  1052. }
  1053. //Gets focus based on scope event name (e.g. focus-on='SomeEventName')
  1054. if (angular.isDefined(attrs.focusOn)){
  1055. scope.$on(attrs.focusOn, function() {
  1056. $timeout(function(){
  1057. $select.setFocus();
  1058. });
  1059. });
  1060. }
  1061. function onDocumentClick(e) {
  1062. if (!$select.open) return; //Skip it if dropdown is close
  1063. var contains = false;
  1064. if (window.jQuery) {
  1065. // Firefox 3.6 does not support element.contains()
  1066. // See Node.contains https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
  1067. contains = window.jQuery.contains(element[0], e.target);
  1068. } else {
  1069. contains = element[0].contains(e.target);
  1070. }
  1071. if (!contains && !$select.clickTriggeredSelect) {
  1072. var skipFocusser;
  1073. if (!$select.skipFocusser) {
  1074. //Will lose focus only with certain targets
  1075. var focusableControls = ['input','button','textarea','select'];
  1076. var targetController = angular.element(e.target).controller('uiSelect'); //To check if target is other ui-select
  1077. skipFocusser = targetController && targetController !== $select; //To check if target is other ui-select
  1078. if (!skipFocusser) skipFocusser = ~focusableControls.indexOf(e.target.tagName.toLowerCase()); //Check if target is input, button or textarea
  1079. } else {
  1080. skipFocusser = true;
  1081. }
  1082. $select.close(skipFocusser);
  1083. scope.$digest();
  1084. }
  1085. $select.clickTriggeredSelect = false;
  1086. }
  1087. // See Click everywhere but here event http://stackoverflow.com/questions/12931369
  1088. $document.on('click', onDocumentClick);
  1089. scope.$on('$destroy', function() {
  1090. $document.off('click', onDocumentClick);
  1091. });
  1092. // Move transcluded elements to their correct position in main template
  1093. transcludeFn(scope, function(clone) {
  1094. // See Transclude in AngularJS http://blog.omkarpatil.com/2012/11/transclude-in-angularjs.html
  1095. // One day jqLite will be replaced by jQuery and we will be able to write:
  1096. // var transcludedElement = clone.filter('.my-class')
  1097. // instead of creating a hackish DOM element:
  1098. var transcluded = angular.element('<div>').append(clone);
  1099. var transcludedMatch = transcluded.querySelectorAll('.ui-select-match');
  1100. transcludedMatch.removeAttr('ui-select-match'); //To avoid loop in case directive as attr
  1101. transcludedMatch.removeAttr('data-ui-select-match'); // Properly handle HTML5 data-attributes
  1102. if (transcludedMatch.length !== 1) {
  1103. throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-match but got '{0}'.", transcludedMatch.length);
  1104. }
  1105. element.querySelectorAll('.ui-select-match').replaceWith(transcludedMatch);
  1106. var transcludedChoices = transcluded.querySelectorAll('.ui-select-choices');
  1107. transcludedChoices.removeAttr('ui-select-choices'); //To avoid loop in case directive as attr
  1108. transcludedChoices.removeAttr('data-ui-select-choices'); // Properly handle HTML5 data-attributes
  1109. if (transcludedChoices.length !== 1) {
  1110. throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-choices but got '{0}'.", transcludedChoices.length);
  1111. }
  1112. element.querySelectorAll('.ui-select-choices').replaceWith(transcludedChoices);
  1113. var transcludedNoChoice = transcluded.querySelectorAll('.ui-select-no-choice');
  1114. transcludedNoChoice.removeAttr('ui-select-no-choice'); //To avoid loop in case directive as attr
  1115. transcludedNoChoice.removeAttr('data-ui-select-no-choice'); // Properly handle HTML5 data-attributes
  1116. if (transcludedNoChoice.length == 1) {
  1117. element.querySelectorAll('.ui-select-no-choice').replaceWith(transcludedNoChoice);
  1118. }
  1119. });
  1120. // Support for appending the select field to the body when its open
  1121. var appendToBody = scope.$eval(attrs.appendToBody);
  1122. if (appendToBody !== undefined ? appendToBody : uiSelectConfig.appendToBody) {
  1123. scope.$watch('$select.open', function(isOpen) {
  1124. if (isOpen) {
  1125. positionDropdown();
  1126. } else {
  1127. resetDropdown();
  1128. }
  1129. });
  1130. // Move the dropdown back to its original location when the scope is destroyed. Otherwise
  1131. // it might stick around when the user routes away or the select field is otherwise removed
  1132. scope.$on('$destroy', function() {
  1133. resetDropdown();
  1134. });
  1135. }
  1136. // Hold on to a reference to the .ui-select-container element for appendToBody support
  1137. var placeholder = null,
  1138. originalWidth = '';
  1139. function positionDropdown() {
  1140. // Remember the absolute position of the element
  1141. var offset = uisOffset(element);
  1142. // Clone the element into a placeholder element to take its original place in the DOM
  1143. placeholder = angular.element('<div class="ui-select-placeholder"></div>');
  1144. placeholder[0].style.width = offset.width + 'px';
  1145. placeholder[0].style.height = offset.height + 'px';
  1146. element.after(placeholder);
  1147. // Remember the original value of the element width inline style, so it can be restored
  1148. // when the dropdown is closed
  1149. originalWidth = element[0].style.width;
  1150. // Now move the actual dropdown element to the end of the body
  1151. $document.find('body').append(element);
  1152. element[0].style.position = 'absolute';
  1153. element[0].style.left = offset.left + 'px';
  1154. element[0].style.top = offset.top + 'px';
  1155. element[0].style.width = offset.width + 'px';
  1156. }
  1157. function resetDropdown() {
  1158. if (placeholder === null) {
  1159. // The dropdown has not actually been display yet, so there's nothing to reset
  1160. return;
  1161. }
  1162. // Move the dropdown element back to its original location in the DOM
  1163. placeholder.replaceWith(element);
  1164. placeholder = null;
  1165. element[0].style.position = '';
  1166. element[0].style.left = '';
  1167. element[0].style.top = '';
  1168. element[0].style.width = originalWidth;
  1169. // Set focus back on to the moved element
  1170. $select.setFocus();
  1171. }
  1172. // Hold on to a reference to the .ui-select-dropdown element for direction support.
  1173. var dropdown = null,
  1174. directionUpClassName = 'direction-up';
  1175. // Support changing the direction of the dropdown if there isn't enough space to render it.
  1176. scope.$watch('$select.open', function() {
  1177. if ($select.dropdownPosition === 'auto' || $select.dropdownPosition === 'up'){
  1178. scope.calculateDropdownPos();
  1179. }
  1180. });
  1181. var setDropdownPosUp = function(offset, offsetDropdown){
  1182. offset = offset || uisOffset(element);
  1183. offsetDropdown = offsetDropdown || uisOffset(dropdown);
  1184. dropdown[0].style.position = 'absolute';
  1185. dropdown[0].style.top = (offsetDropdown.height * -1) + 'px';
  1186. element.addClass(directionUpClassName);
  1187. };
  1188. var setDropdownPosDown = function(offset, offsetDropdown){
  1189. element.removeClass(directionUpClassName);
  1190. offset = offset || uisOffset(element);
  1191. offsetDropdown = offsetDropdown || uisOffset(dropdown);
  1192. dropdown[0].style.position = '';
  1193. dropdown[0].style.top = '';
  1194. };
  1195. var calculateDropdownPosAfterAnimation = function() {
  1196. // Delay positioning the dropdown until all choices have been added so its height is correct.
  1197. $timeout(function() {
  1198. if ($select.dropdownPosition === 'up') {
  1199. //Go UP
  1200. setDropdownPosUp();
  1201. } else {
  1202. //AUTO
  1203. element.removeClass(directionUpClassName);
  1204. var offset = uisOffset(element);
  1205. var offsetDropdown = uisOffset(dropdown);
  1206. //https://code.google.com/p/chromium/issues/detail?id=342307#c4
  1207. var scrollTop = $document[0].documentElement.scrollTop || $document[0].body.scrollTop; //To make it cross browser (blink, webkit, IE, Firefox).
  1208. // Determine if the direction of the dropdown needs to be changed.
  1209. if (offset.top + offset.height + offsetDropdown.height > scrollTop + $document[0].documentElement.clientHeight) {
  1210. //Go UP
  1211. setDropdownPosUp(offset, offsetDropdown);
  1212. }else{
  1213. //Go DOWN
  1214. setDropdownPosDown(offset, offsetDropdown);
  1215. }
  1216. }
  1217. // Display the dropdown once it has been positioned.
  1218. dropdown[0].style.opacity = 1;
  1219. });
  1220. };
  1221. var opened = false;
  1222. scope.calculateDropdownPos = function() {
  1223. if ($select.open) {
  1224. dropdown = angular.element(element).querySelectorAll('.ui-select-dropdown');
  1225. if (dropdown.length === 0) {
  1226. return;
  1227. }
  1228. // Hide the dropdown so there is no flicker until $timeout is done executing.
  1229. if ($select.search === '' && !opened) {
  1230. dropdown[0].style.opacity = 0;
  1231. opened = true;
  1232. }
  1233. if (!uisOffset(dropdown).height && $select.$animate && $select.$animate.on && $select.$animate.enabled(dropdown)) {
  1234. var needsCalculated = true;
  1235. $select.$animate.on('enter', dropdown, function (elem, phase) {
  1236. if (phase === 'close' && needsCalculated) {
  1237. calculateDropdownPosAfterAnimation();
  1238. needsCalculated = false;
  1239. }
  1240. });
  1241. } else {
  1242. calculateDropdownPosAfterAnimation();
  1243. }
  1244. } else {
  1245. if (dropdown === null || dropdown.length === 0) {
  1246. return;
  1247. }
  1248. // Reset the position of the dropdown.
  1249. dropdown[0].style.opacity = 0;
  1250. dropdown[0].style.position = '';
  1251. dropdown[0].style.top = '';
  1252. element.removeClass(directionUpClassName);
  1253. }
  1254. };
  1255. };
  1256. }
  1257. };
  1258. }]);
  1259. uis.directive('uiSelectMatch', ['uiSelectConfig', function(uiSelectConfig) {
  1260. return {
  1261. restrict: 'EA',
  1262. require: '^uiSelect',
  1263. replace: true,
  1264. transclude: true,
  1265. templateUrl: function(tElement) {
  1266. // Needed so the uiSelect can detect the transcluded content
  1267. tElement.addClass('ui-select-match');
  1268. var parent = tElement.parent();
  1269. // Gets theme attribute from parent (ui-select)
  1270. var theme = getAttribute(parent, 'theme') || uiSelectConfig.theme;
  1271. var multi = angular.isDefined(getAttribute(parent, 'multiple'));
  1272. return theme + (multi ? '/match-multiple.tpl.html' : '/match.tpl.html');
  1273. },
  1274. link: function(scope, element, attrs, $select) {
  1275. $select.lockChoiceExpression = attrs.uiLockChoice;
  1276. attrs.$observe('placeholder', function(placeholder) {
  1277. $select.placeholder = placeholder !== undefined ? placeholder : uiSelectConfig.placeholder;
  1278. });
  1279. function setAllowClear(allow) {
  1280. $select.allowClear = (angular.isDefined(allow)) ? (allow === '') ? true : (allow.toLowerCase() === 'true') : false;
  1281. }
  1282. attrs.$observe('allowClear', setAllowClear);
  1283. setAllowClear(attrs.allowClear);
  1284. if($select.multiple){
  1285. $select.sizeSearchInput();
  1286. }
  1287. }
  1288. };
  1289. function getAttribute(elem, attribute) {
  1290. if (elem[0].hasAttribute(attribute))
  1291. return elem.attr(attribute);
  1292. if (elem[0].hasAttribute('data-' + attribute))
  1293. return elem.attr('data-' + attribute);
  1294. if (elem[0].hasAttribute('x-' + attribute))
  1295. return elem.attr('x-' + attribute);
  1296. }
  1297. }]);
  1298. uis.directive('uiSelectMultiple', ['uiSelectMinErr','$timeout', function(uiSelectMinErr, $timeout) {
  1299. return {
  1300. restrict: 'EA',
  1301. require: ['^uiSelect', '^ngModel'],
  1302. controller: ['$scope','$timeout', function($scope, $timeout){
  1303. var ctrl = this,
  1304. $select = $scope.$select,
  1305. ngModel;
  1306. if (angular.isUndefined($select.selected))
  1307. $select.selected = [];
  1308. //Wait for link fn to inject it
  1309. $scope.$evalAsync(function(){ ngModel = $scope.ngModel; });
  1310. ctrl.activeMatchIndex = -1;
  1311. ctrl.updateModel = function(){
  1312. ngModel.$setViewValue(Date.now()); //Set timestamp as a unique string to force changes
  1313. ctrl.refreshComponent();
  1314. };
  1315. ctrl.refreshComponent = function(){
  1316. //Remove already selected items
  1317. //e.g. When user clicks on a selection, the selected array changes and
  1318. //the dropdown should remove that item
  1319. if($select.refreshItems){
  1320. $select.refreshItems();
  1321. }
  1322. if($select.sizeSearchInput){
  1323. $select.sizeSearchInput();
  1324. }
  1325. };
  1326. // Remove item from multiple select
  1327. ctrl.removeChoice = function(index){
  1328. // if the choice is locked, don't remove it
  1329. if($select.isLocked(null, index)) return false;
  1330. var removedChoice = $select.selected[index];
  1331. var locals = {};
  1332. locals[$select.parserResult.itemName] = removedChoice;
  1333. $select.selected.splice(index, 1);
  1334. ctrl.activeMatchIndex = -1;
  1335. $select.sizeSearchInput();
  1336. // Give some time for scope propagation.
  1337. $timeout(function(){
  1338. $select.onRemoveCallback($scope, {
  1339. $item: removedChoice,
  1340. $model: $select.parserResult.modelMapper($scope, locals)
  1341. });
  1342. });
  1343. ctrl.updateModel();
  1344. return true;
  1345. };
  1346. ctrl.getPlaceholder = function(){
  1347. //Refactor single?
  1348. if($select.selected && $select.selected.length) return;
  1349. return $select.placeholder;
  1350. };
  1351. }],
  1352. controllerAs: '$selectMultiple',
  1353. link: function(scope, element, attrs, ctrls) {
  1354. var $select = ctrls[0];
  1355. var ngModel = scope.ngModel = ctrls[1];
  1356. var $selectMultiple = scope.$selectMultiple;
  1357. //$select.selected = raw selected objects (ignoring any property binding)
  1358. $select.multiple = true;
  1359. //Input that will handle focus
  1360. $select.focusInput = $select.searchInput;
  1361. //Properly check for empty if set to multiple
  1362. ngModel.$isEmpty = function(value) {
  1363. return !value || value.length === 0;
  1364. };
  1365. //From view --> model
  1366. ngModel.$parsers.unshift(function () {
  1367. var locals = {},
  1368. result,
  1369. resultMultiple = [];
  1370. for (var j = $select.selected.length - 1; j >= 0; j--) {
  1371. locals = {};
  1372. locals[$select.parserResult.itemName] = $select.selected[j];
  1373. result = $select.parserResult.modelMapper(scope, locals);
  1374. resultMultiple.unshift(result);
  1375. }
  1376. return resultMultiple;
  1377. });
  1378. // From model --> view
  1379. ngModel.$formatters.unshift(function (inputValue) {
  1380. var data = $select.parserResult && $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search
  1381. locals = {},
  1382. result;
  1383. if (!data) return inputValue;
  1384. var resultMultiple = [];
  1385. var checkFnMultiple = function(list, value){
  1386. if (!list || !list.length) return;
  1387. for (var p = list.length - 1; p >= 0; p--) {
  1388. locals[$select.parserResult.itemName] = list[p];
  1389. result = $select.parserResult.modelMapper(scope, locals);
  1390. if($select.parserResult.trackByExp){
  1391. var propsItemNameMatches = /(\w*)\./.exec($select.parserResult.trackByExp);
  1392. var matches = /\.([^\s]+)/.exec($select.parserResult.trackByExp);
  1393. if(propsItemNameMatches && propsItemNameMatches.length > 0 && propsItemNameMatches[1] == $select.parserResult.itemName){
  1394. if(matches && matches.length>0 && result[matches[1]] == value[matches[1]]){
  1395. resultMultiple.unshift(list[p]);
  1396. return true;
  1397. }
  1398. }
  1399. }
  1400. if (angular.equals(result,value)){
  1401. resultMultiple.unshift(list[p]);
  1402. return true;
  1403. }
  1404. }
  1405. return false;
  1406. };
  1407. if (!inputValue) return resultMultiple; //If ngModel was undefined
  1408. for (var k = inputValue.length - 1; k >= 0; k--) {
  1409. //Check model array of currently selected items
  1410. if (!checkFnMultiple($select.selected, inputValue[k])){
  1411. //Check model array of all items available
  1412. if (!checkFnMultiple(data, inputValue[k])){
  1413. //If not found on previous lists, just add it directly to resultMultiple
  1414. resultMultiple.unshift(inputValue[k]);
  1415. }
  1416. }
  1417. }
  1418. return resultMultiple;
  1419. });
  1420. //Watch for external model changes
  1421. scope.$watchCollection(function(){ return ngModel.$modelValue; }, function(newValue, oldValue) {
  1422. if (oldValue != newValue){
  1423. //update the view value with fresh data from items, if there is a valid model value
  1424. if(angular.isDefined(ngModel.$modelValue)) {
  1425. ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters
  1426. }
  1427. $selectMultiple.refreshComponent();
  1428. }
  1429. });
  1430. ngModel.$render = function() {
  1431. // Make sure that model value is array
  1432. if(!angular.isArray(ngModel.$viewValue)){
  1433. // Have tolerance for null or undefined values
  1434. if (isNil(ngModel.$viewValue)){
  1435. ngModel.$viewValue = [];
  1436. } else {
  1437. throw uiSelectMinErr('multiarr', "Expected model value to be array but got '{0}'", ngModel.$viewValue);
  1438. }
  1439. }
  1440. $select.selected = ngModel.$viewValue;
  1441. $selectMultiple.refreshComponent();
  1442. scope.$evalAsync(); //To force $digest
  1443. };
  1444. scope.$on('uis:select', function (event, item) {
  1445. if($select.selected.length >= $select.limit) {
  1446. return;
  1447. }
  1448. $select.selected.push(item);
  1449. var locals = {};
  1450. locals[$select.parserResult.itemName] = item;
  1451. $timeout(function(){
  1452. $select.onSelectCallback(scope, {
  1453. $item: item,
  1454. $model: $select.parserResult.modelMapper(scope, locals)
  1455. });
  1456. });
  1457. $selectMultiple.updateModel();
  1458. });
  1459. scope.$on('uis:activate', function () {
  1460. $selectMultiple.activeMatchIndex = -1;
  1461. });
  1462. scope.$watch('$select.disabled', function(newValue, oldValue) {
  1463. // As the search input field may now become visible, it may be necessary to recompute its size
  1464. if (oldValue && !newValue) $select.sizeSearchInput();
  1465. });
  1466. $select.searchInput.on('keydown', function(e) {
  1467. var key = e.which;
  1468. scope.$apply(function() {
  1469. var processed = false;
  1470. // var tagged = false; //Checkme
  1471. if(KEY.isHorizontalMovement(key)){
  1472. processed = _handleMatchSelection(key);
  1473. }
  1474. if (processed && key != KEY.TAB) {
  1475. //TODO Check si el tab selecciona aun correctamente
  1476. //Crear test
  1477. e.preventDefault();
  1478. e.stopPropagation();
  1479. }
  1480. });
  1481. });
  1482. function _getCaretPosition(el) {
  1483. if(angular.isNumber(el.selectionStart)) return el.selectionStart;
  1484. // selectionStart is not supported in IE8 and we don't want hacky workarounds so we compromise
  1485. else return el.value.length;
  1486. }
  1487. // Handles selected options in "multiple" mode
  1488. function _handleMatchSelection(key){
  1489. var caretPosition = _getCaretPosition($select.searchInput[0]),
  1490. length = $select.selected.length,
  1491. // none = -1,
  1492. first = 0,
  1493. last = length-1,
  1494. curr = $selectMultiple.activeMatchIndex,
  1495. next = $selectMultiple.activeMatchIndex+1,
  1496. prev = $selectMultiple.activeMatchIndex-1,
  1497. newIndex = curr;
  1498. if(caretPosition > 0 || ($select.search.length && key == KEY.RIGHT)) return false;
  1499. $select.close();
  1500. function getNewActiveMatchIndex(){
  1501. switch(key){
  1502. case KEY.LEFT:
  1503. // Select previous/first item
  1504. if(~$selectMultiple.activeMatchIndex) return prev;
  1505. // Select last item
  1506. else return last;
  1507. break;
  1508. case KEY.RIGHT:
  1509. // Open drop-down
  1510. if(!~$selectMultiple.activeMatchIndex || curr === last){
  1511. $select.activate();
  1512. return false;
  1513. }
  1514. // Select next/last item
  1515. else return next;
  1516. break;
  1517. case KEY.BACKSPACE:
  1518. // Remove selected item and select previous/first
  1519. if(~$selectMultiple.activeMatchIndex){
  1520. if($selectMultiple.removeChoice(curr)) {
  1521. return prev;
  1522. } else {
  1523. return curr;
  1524. }
  1525. } else {
  1526. // If nothing yet selected, select last item
  1527. return last;
  1528. }
  1529. break;
  1530. case KEY.DELETE:
  1531. // Remove selected item and select next item
  1532. if(~$selectMultiple.activeMatchIndex){
  1533. $selectMultiple.removeChoice($selectMultiple.activeMatchIndex);
  1534. return curr;
  1535. }
  1536. else return false;
  1537. }
  1538. }
  1539. newIndex = getNewActiveMatchIndex();
  1540. if(!$select.selected.length || newIndex === false) $selectMultiple.activeMatchIndex = -1;
  1541. else $selectMultiple.activeMatchIndex = Math.min(last,Math.max(first,newIndex));
  1542. return true;
  1543. }
  1544. $select.searchInput.on('keyup', function(e) {
  1545. if ( ! KEY.isVerticalMovement(e.which) ) {
  1546. scope.$evalAsync( function () {
  1547. $select.activeIndex = $select.taggingLabel === false ? -1 : 0;
  1548. });
  1549. }
  1550. // Push a "create new" item into array if there is a search string
  1551. if ( $select.tagging.isActivated && $select.search.length > 0 ) {
  1552. // return early with these keys
  1553. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || KEY.isVerticalMovement(e.which) ) {
  1554. return;
  1555. }
  1556. // always reset the activeIndex to the first item when tagging
  1557. $select.activeIndex = $select.taggingLabel === false ? -1 : 0;
  1558. // taggingLabel === false bypasses all of this
  1559. if ($select.taggingLabel === false) return;
  1560. var items = angular.copy( $select.items );
  1561. var stashArr = angular.copy( $select.items );
  1562. var newItem;
  1563. var item;
  1564. var hasTag = false;
  1565. var dupeIndex = -1;
  1566. var tagItems;
  1567. var tagItem;
  1568. // case for object tagging via transform `$select.tagging.fct` function
  1569. if ( $select.tagging.fct !== undefined) {
  1570. tagItems = $select.$filter('filter')(items,{'isTag': true});
  1571. if ( tagItems.length > 0 ) {
  1572. tagItem = tagItems[0];
  1573. }
  1574. // remove the first element, if it has the `isTag` prop we generate a new one with each keyup, shaving the previous
  1575. if ( items.length > 0 && tagItem ) {
  1576. hasTag = true;
  1577. items = items.slice(1,items.length);
  1578. stashArr = stashArr.slice(1,stashArr.length);
  1579. }
  1580. newItem = $select.tagging.fct($select.search);
  1581. // verify the new tag doesn't match the value of a possible selection choice or an already selected item.
  1582. if (
  1583. stashArr.some(function (origItem) {
  1584. return angular.equals(origItem, newItem);
  1585. }) ||
  1586. $select.selected.some(function (origItem) {
  1587. return angular.equals(origItem, newItem);
  1588. })
  1589. ) {
  1590. scope.$evalAsync(function () {
  1591. $select.activeIndex = 0;
  1592. $select.items = items;
  1593. });
  1594. return;
  1595. }
  1596. if (newItem) newItem.isTag = true;
  1597. // handle newItem string and stripping dupes in tagging string context
  1598. } else {
  1599. // find any tagging items already in the $select.items array and store them
  1600. tagItems = $select.$filter('filter')(items,function (item) {
  1601. return item.match($select.taggingLabel);
  1602. });
  1603. if ( tagItems.length > 0 ) {
  1604. tagItem = tagItems[0];
  1605. }
  1606. item = items[0];
  1607. // remove existing tag item if found (should only ever be one tag item)
  1608. if ( item !== undefined && items.length > 0 && tagItem ) {
  1609. hasTag = true;
  1610. items = items.slice(1,items.length);
  1611. stashArr = stashArr.slice(1,stashArr.length);
  1612. }
  1613. newItem = $select.search+' '+$select.taggingLabel;
  1614. if ( _findApproxDupe($select.selected, $select.search) > -1 ) {
  1615. return;
  1616. }
  1617. // verify the the tag doesn't match the value of an existing item from
  1618. // the searched data set or the items already selected
  1619. if ( _findCaseInsensitiveDupe(stashArr.concat($select.selected)) ) {
  1620. // if there is a tag from prev iteration, strip it / queue the change
  1621. // and return early
  1622. if ( hasTag ) {
  1623. items = stashArr;
  1624. scope.$evalAsync( function () {
  1625. $select.activeIndex = 0;
  1626. $select.items = items;
  1627. });
  1628. }
  1629. return;
  1630. }
  1631. if ( _findCaseInsensitiveDupe(stashArr) ) {
  1632. // if there is a tag from prev iteration, strip it
  1633. if ( hasTag ) {
  1634. $select.items = stashArr.slice(1,stashArr.length);
  1635. }
  1636. return;
  1637. }
  1638. }
  1639. if ( hasTag ) dupeIndex = _findApproxDupe($select.selected, newItem);
  1640. // dupe found, shave the first item
  1641. if ( dupeIndex > -1 ) {
  1642. items = items.slice(dupeIndex+1,items.length-1);
  1643. } else {
  1644. items = [];
  1645. if (newItem) items.push(newItem);
  1646. items = items.concat(stashArr);
  1647. }
  1648. scope.$evalAsync( function () {
  1649. $select.activeIndex = 0;
  1650. $select.items = items;
  1651. if ($select.isGrouped) {
  1652. // update item references in groups, so that indexOf will work after angular.copy
  1653. var itemsWithoutTag = newItem ? items.slice(1) : items;
  1654. $select.setItemsFn(itemsWithoutTag);
  1655. if (newItem) {
  1656. // add tag item as a new group
  1657. $select.items.unshift(newItem);
  1658. $select.groups.unshift({name: '', items: [newItem], tagging: true});
  1659. }
  1660. }
  1661. });
  1662. }
  1663. });
  1664. function _findCaseInsensitiveDupe(arr) {
  1665. if ( arr === undefined || $select.search === undefined ) {
  1666. return false;
  1667. }
  1668. var hasDupe = arr.filter( function (origItem) {
  1669. if ( $select.search.toUpperCase() === undefined || origItem === undefined ) {
  1670. return false;
  1671. }
  1672. return origItem.toUpperCase() === $select.search.toUpperCase();
  1673. }).length > 0;
  1674. return hasDupe;
  1675. }
  1676. function _findApproxDupe(haystack, needle) {
  1677. var dupeIndex = -1;
  1678. if(angular.isArray(haystack)) {
  1679. var tempArr = angular.copy(haystack);
  1680. for (var i = 0; i <tempArr.length; i++) {
  1681. // handle the simple string version of tagging
  1682. if ( $select.tagging.fct === undefined ) {
  1683. // search the array for the match
  1684. if ( tempArr[i]+' '+$select.taggingLabel === needle ) {
  1685. dupeIndex = i;
  1686. }
  1687. // handle the object tagging implementation
  1688. } else {
  1689. var mockObj = tempArr[i];
  1690. if (angular.isObject(mockObj)) {
  1691. mockObj.isTag = true;
  1692. }
  1693. if ( angular.equals(mockObj, needle) ) {
  1694. dupeIndex = i;
  1695. }
  1696. }
  1697. }
  1698. }
  1699. return dupeIndex;
  1700. }
  1701. $select.searchInput.on('blur', function() {
  1702. $timeout(function() {
  1703. $selectMultiple.activeMatchIndex = -1;
  1704. });
  1705. });
  1706. }
  1707. };
  1708. }]);
  1709. uis.directive('uiSelectNoChoice',
  1710. ['uiSelectConfig', function (uiSelectConfig) {
  1711. return {
  1712. restrict: 'EA',
  1713. require: '^uiSelect',
  1714. replace: true,
  1715. transclude: true,
  1716. templateUrl: function (tElement) {
  1717. // Needed so the uiSelect can detect the transcluded content
  1718. tElement.addClass('ui-select-no-choice');
  1719. // Gets theme attribute from parent (ui-select)
  1720. var theme = tElement.parent().attr('theme') || uiSelectConfig.theme;
  1721. return theme + '/no-choice.tpl.html';
  1722. }
  1723. };
  1724. }]);
  1725. uis.directive('uiSelectSingle', ['$timeout','$compile', function($timeout, $compile) {
  1726. return {
  1727. restrict: 'EA',
  1728. require: ['^uiSelect', '^ngModel'],
  1729. link: function(scope, element, attrs, ctrls) {
  1730. var $select = ctrls[0];
  1731. var ngModel = ctrls[1];
  1732. //From view --> model
  1733. ngModel.$parsers.unshift(function (inputValue) {
  1734. // Keep original value for undefined and null
  1735. if (isNil(inputValue)) {
  1736. return inputValue;
  1737. }
  1738. var locals = {},
  1739. result;
  1740. locals[$select.parserResult.itemName] = inputValue;
  1741. result = $select.parserResult.modelMapper(scope, locals);
  1742. return result;
  1743. });
  1744. //From model --> view
  1745. ngModel.$formatters.unshift(function (inputValue) {
  1746. // Keep original value for undefined and null
  1747. if (isNil(inputValue)) {
  1748. return inputValue;
  1749. }
  1750. var data = $select.parserResult && $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search
  1751. locals = {},
  1752. result;
  1753. if (data){
  1754. var checkFnSingle = function(d){
  1755. locals[$select.parserResult.itemName] = d;
  1756. result = $select.parserResult.modelMapper(scope, locals);
  1757. return result === inputValue;
  1758. };
  1759. //If possible pass same object stored in $select.selected
  1760. if ($select.selected && checkFnSingle($select.selected)) {
  1761. return $select.selected;
  1762. }
  1763. for (var i = data.length - 1; i >= 0; i--) {
  1764. if (checkFnSingle(data[i])) return data[i];
  1765. }
  1766. }
  1767. return inputValue;
  1768. });
  1769. //Update viewValue if model change
  1770. scope.$watch('$select.selected', function(newValue) {
  1771. if (ngModel.$viewValue !== newValue) {
  1772. ngModel.$setViewValue(newValue);
  1773. }
  1774. });
  1775. ngModel.$render = function() {
  1776. $select.selected = ngModel.$viewValue;
  1777. };
  1778. scope.$on('uis:select', function (event, item) {
  1779. $select.selected = item;
  1780. var locals = {};
  1781. locals[$select.parserResult.itemName] = item;
  1782. $timeout(function() {
  1783. $select.onSelectCallback(scope, {
  1784. $item: item,
  1785. $model: isNil(item) ? item : $select.parserResult.modelMapper(scope, locals)
  1786. });
  1787. });
  1788. });
  1789. scope.$on('uis:close', function (event, skipFocusser) {
  1790. $timeout(function(){
  1791. $select.focusser.prop('disabled', false);
  1792. if (!skipFocusser) $select.focusser[0].focus();
  1793. },0,false);
  1794. });
  1795. scope.$on('uis:activate', function () {
  1796. focusser.prop('disabled', true); //Will reactivate it on .close()
  1797. });
  1798. //Idea from: https://github.com/ivaynberg/select2/blob/79b5bf6db918d7560bdd959109b7bcfb47edaf43/select2.js#L1954
  1799. var focusser = angular.element("<input ng-disabled='$select.disabled' class='ui-select-focusser ui-select-offscreen' type='text' id='{{ $select.focusserId }}' aria-label='{{ $select.focusserTitle }}' aria-haspopup='true' role='button' />");
  1800. $compile(focusser)(scope);
  1801. $select.focusser = focusser;
  1802. //Input that will handle focus
  1803. $select.focusInput = focusser;
  1804. element.parent().append(focusser);
  1805. focusser.bind("focus", function(){
  1806. scope.$evalAsync(function(){
  1807. $select.focus = true;
  1808. });
  1809. });
  1810. focusser.bind("blur", function(){
  1811. scope.$evalAsync(function(){
  1812. $select.focus = false;
  1813. });
  1814. });
  1815. focusser.bind("keydown", function(e){
  1816. if (e.which === KEY.BACKSPACE && $select.backspaceReset !== false) {
  1817. e.preventDefault();
  1818. e.stopPropagation();
  1819. $select.select(undefined);
  1820. scope.$apply();
  1821. return;
  1822. }
  1823. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
  1824. return;
  1825. }
  1826. if (e.which == KEY.DOWN || e.which == KEY.UP || e.which == KEY.ENTER || e.which == KEY.SPACE){
  1827. e.preventDefault();
  1828. e.stopPropagation();
  1829. $select.activate();
  1830. }
  1831. scope.$digest();
  1832. });
  1833. focusser.bind("keyup input", function(e){
  1834. if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || e.which == KEY.ENTER || e.which === KEY.BACKSPACE) {
  1835. return;
  1836. }
  1837. $select.activate(focusser.val()); //User pressed some regular key, so we pass it to the search input
  1838. focusser.val('');
  1839. scope.$digest();
  1840. });
  1841. }
  1842. };
  1843. }]);
  1844. // Make multiple matches sortable
  1845. uis.directive('uiSelectSort', ['$timeout', 'uiSelectConfig', 'uiSelectMinErr', function($timeout, uiSelectConfig, uiSelectMinErr) {
  1846. return {
  1847. require: ['^^uiSelect', '^ngModel'],
  1848. link: function(scope, element, attrs, ctrls) {
  1849. if (scope[attrs.uiSelectSort] === null) {
  1850. throw uiSelectMinErr('sort', 'Expected a list to sort');
  1851. }
  1852. var $select = ctrls[0];
  1853. var $ngModel = ctrls[1];
  1854. var options = angular.extend({
  1855. axis: 'horizontal'
  1856. },
  1857. scope.$eval(attrs.uiSelectSortOptions));
  1858. var axis = options.axis;
  1859. var draggingClassName = 'dragging';
  1860. var droppingClassName = 'dropping';
  1861. var droppingBeforeClassName = 'dropping-before';
  1862. var droppingAfterClassName = 'dropping-after';
  1863. scope.$watch(function(){
  1864. return $select.sortable;
  1865. }, function(newValue){
  1866. if (newValue) {
  1867. element.attr('draggable', true);
  1868. } else {
  1869. element.removeAttr('draggable');
  1870. }
  1871. });
  1872. element.on('dragstart', function(event) {
  1873. element.addClass(draggingClassName);
  1874. (event.dataTransfer || event.originalEvent.dataTransfer).setData('text', scope.$index.toString());
  1875. });
  1876. element.on('dragend', function() {
  1877. removeClass(draggingClassName);
  1878. });
  1879. var move = function(from, to) {
  1880. /*jshint validthis: true */
  1881. this.splice(to, 0, this.splice(from, 1)[0]);
  1882. };
  1883. var removeClass = function(className) {
  1884. angular.forEach($select.$element.querySelectorAll('.' + className), function(el){
  1885. angular.element(el).removeClass(className);
  1886. });
  1887. };
  1888. var dragOverHandler = function(event) {
  1889. event.preventDefault();
  1890. var offset = axis === 'vertical' ? event.offsetY || event.layerY || (event.originalEvent ? event.originalEvent.offsetY : 0) : event.offsetX || event.layerX || (event.originalEvent ? event.originalEvent.offsetX : 0);
  1891. if (offset < (this[axis === 'vertical' ? 'offsetHeight' : 'offsetWidth'] / 2)) {
  1892. removeClass(droppingAfterClassName);
  1893. element.addClass(droppingBeforeClassName);
  1894. } else {
  1895. removeClass(droppingBeforeClassName);
  1896. element.addClass(droppingAfterClassName);
  1897. }
  1898. };
  1899. var dropTimeout;
  1900. var dropHandler = function(event) {
  1901. event.preventDefault();
  1902. var droppedItemIndex = parseInt((event.dataTransfer || event.originalEvent.dataTransfer).getData('text'), 10);
  1903. // prevent event firing multiple times in firefox
  1904. $timeout.cancel(dropTimeout);
  1905. dropTimeout = $timeout(function() {
  1906. _dropHandler(droppedItemIndex);
  1907. }, 20);
  1908. };
  1909. var _dropHandler = function(droppedItemIndex) {
  1910. var theList = scope.$eval(attrs.uiSelectSort);
  1911. var itemToMove = theList[droppedItemIndex];
  1912. var newIndex = null;
  1913. if (element.hasClass(droppingBeforeClassName)) {
  1914. if (droppedItemIndex < scope.$index) {
  1915. newIndex = scope.$index - 1;
  1916. } else {
  1917. newIndex = scope.$index;
  1918. }
  1919. } else {
  1920. if (droppedItemIndex < scope.$index) {
  1921. newIndex = scope.$index;
  1922. } else {
  1923. newIndex = scope.$index + 1;
  1924. }
  1925. }
  1926. move.apply(theList, [droppedItemIndex, newIndex]);
  1927. $ngModel.$setViewValue(Date.now());
  1928. scope.$apply(function() {
  1929. scope.$emit('uiSelectSort:change', {
  1930. array: theList,
  1931. item: itemToMove,
  1932. from: droppedItemIndex,
  1933. to: newIndex
  1934. });
  1935. });
  1936. removeClass(droppingClassName);
  1937. removeClass(droppingBeforeClassName);
  1938. removeClass(droppingAfterClassName);
  1939. element.off('drop', dropHandler);
  1940. };
  1941. element.on('dragenter', function() {
  1942. if (element.hasClass(draggingClassName)) {
  1943. return;
  1944. }
  1945. element.addClass(droppingClassName);
  1946. element.on('dragover', dragOverHandler);
  1947. element.on('drop', dropHandler);
  1948. });
  1949. element.on('dragleave', function(event) {
  1950. if (event.target != element) {
  1951. return;
  1952. }
  1953. removeClass(droppingClassName);
  1954. removeClass(droppingBeforeClassName);
  1955. removeClass(droppingAfterClassName);
  1956. element.off('dragover', dragOverHandler);
  1957. element.off('drop', dropHandler);
  1958. });
  1959. }
  1960. };
  1961. }]);
  1962. uis.directive('uisOpenClose', ['$parse', '$timeout', function ($parse, $timeout) {
  1963. return {
  1964. restrict: 'A',
  1965. require: 'uiSelect',
  1966. link: function (scope, element, attrs, $select) {
  1967. $select.onOpenCloseCallback = $parse(attrs.uisOpenClose);
  1968. scope.$watch('$select.open', function (isOpen, previousState) {
  1969. if (isOpen !== previousState) {
  1970. $timeout(function () {
  1971. $select.onOpenCloseCallback(scope, {
  1972. isOpen: isOpen
  1973. });
  1974. });
  1975. }
  1976. });
  1977. }
  1978. };
  1979. }]);
  1980. /**
  1981. * Parses "repeat" attribute.
  1982. *
  1983. * Taken from AngularJS ngRepeat source code
  1984. * See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L211
  1985. *
  1986. * Original discussion about parsing "repeat" attribute instead of fully relying on ng-repeat:
  1987. * https://github.com/angular-ui/ui-select/commit/5dd63ad#commitcomment-5504697
  1988. */
  1989. uis.service('uisRepeatParser', ['uiSelectMinErr','$parse', function(uiSelectMinErr, $parse) {
  1990. var self = this;
  1991. /**
  1992. * Example:
  1993. * expression = "address in addresses | filter: {street: $select.search} track by $index"
  1994. * itemName = "address",
  1995. * source = "addresses | filter: {street: $select.search}",
  1996. * trackByExp = "$index",
  1997. */
  1998. self.parse = function(expression) {
  1999. var match;
  2000. //var isObjectCollection = /\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)/.test(expression);
  2001. // If an array is used as collection
  2002. // if (isObjectCollection){
  2003. // 000000000000000000000000000000111111111000000000000000222222222222220033333333333333333333330000444444444444444444000000000000000055555555555000000000000000000000066666666600000000
  2004. match = expression.match(/^\s*(?:([\s\S]+?)\s+as\s+)?(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(\s*[\s\S]+?)?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
  2005. // 1 Alias
  2006. // 2 Item
  2007. // 3 Key on (key,value)
  2008. // 4 Value on (key,value)
  2009. // 5 Source expression (including filters)
  2010. // 6 Track by
  2011. if (!match) {
  2012. throw uiSelectMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  2013. expression);
  2014. }
  2015. var source = match[5],
  2016. filters = '';
  2017. // When using (key,value) ui-select requires filters to be extracted, since the object
  2018. // is converted to an array for $select.items
  2019. // (in which case the filters need to be reapplied)
  2020. if (match[3]) {
  2021. // Remove any enclosing parenthesis
  2022. source = match[5].replace(/(^\()|(\)$)/g, '');
  2023. // match all after | but not after ||
  2024. var filterMatch = match[5].match(/^\s*(?:[\s\S]+?)(?:[^\|]|\|\|)+([\s\S]*)\s*$/);
  2025. if(filterMatch && filterMatch[1].trim()) {
  2026. filters = filterMatch[1];
  2027. source = source.replace(filters, '');
  2028. }
  2029. }
  2030. return {
  2031. itemName: match[4] || match[2], // (lhs) Left-hand side,
  2032. keyName: match[3], //for (key, value) syntax
  2033. source: $parse(source),
  2034. filters: filters,
  2035. trackByExp: match[6],
  2036. modelMapper: $parse(match[1] || match[4] || match[2]),
  2037. repeatExpression: function (grouped) {
  2038. var expression = this.itemName + ' in ' + (grouped ? '$group.items' : '$select.items');
  2039. if (this.trackByExp) {
  2040. expression += ' track by ' + this.trackByExp;
  2041. }
  2042. return expression;
  2043. }
  2044. };
  2045. };
  2046. self.getGroupNgRepeatExpression = function() {
  2047. return '$group in $select.groups track by $group.name';
  2048. };
  2049. }]);
  2050. }());
  2051. angular.module("ui.select").run(["$templateCache", function($templateCache) {$templateCache.put("bootstrap/choices.tpl.html","<ul class=\"ui-select-choices ui-select-choices-content ui-select-dropdown dropdown-menu\" ng-show=\"$select.open && $select.items.length > 0\"><li class=\"ui-select-choices-group\" id=\"ui-select-choices-{{ $select.generatedId }}\"><div class=\"divider\" ng-show=\"$select.isGrouped && $index > 0\"></div><div ng-show=\"$select.isGrouped\" class=\"ui-select-choices-group-label dropdown-header\" ng-bind=\"$group.name\"></div><div ng-attr-id=\"ui-select-choices-row-{{ $select.generatedId }}-{{$index}}\" class=\"ui-select-choices-row\" ng-class=\"{active: $select.isActive(this), disabled: $select.isDisabled(this)}\" role=\"option\"><span class=\"ui-select-choices-row-inner\"></span></div></li></ul>");
  2052. $templateCache.put("bootstrap/match-multiple.tpl.html","<span class=\"ui-select-match\"><span ng-repeat=\"$item in $select.selected track by $index\"><span class=\"ui-select-match-item btn btn-default btn-xs\" tabindex=\"-1\" type=\"button\" ng-disabled=\"$select.disabled\" ng-click=\"$selectMultiple.activeMatchIndex = $index;\" ng-class=\"{\'btn-primary\':$selectMultiple.activeMatchIndex === $index, \'select-locked\':$select.isLocked(this, $index)}\" ui-select-sort=\"$select.selected\"><span class=\"close ui-select-match-close\" ng-hide=\"$select.disabled\" ng-click=\"$selectMultiple.removeChoice($index)\">&nbsp;&times;</span> <span uis-transclude-append=\"\"></span></span></span></span>");
  2053. $templateCache.put("bootstrap/match.tpl.html","<div class=\"ui-select-match\" ng-hide=\"$select.open && $select.searchEnabled\" ng-disabled=\"$select.disabled\" ng-class=\"{\'btn-default-focus\':$select.focus}\"><span tabindex=\"-1\" class=\"btn btn-default form-control ui-select-toggle\" aria-label=\"{{ $select.baseTitle }} activate\" ng-disabled=\"$select.disabled\" ng-click=\"$select.activate()\" style=\"outline: 0;\"><span ng-show=\"$select.isEmpty()\" class=\"ui-select-placeholder text-muted\">{{$select.placeholder}}</span> <span ng-hide=\"$select.isEmpty()\" class=\"ui-select-match-text pull-left\" ng-class=\"{\'ui-select-allow-clear\': $select.allowClear && !$select.isEmpty()}\" ng-transclude=\"\"></span> <i class=\"caret pull-right\" ng-click=\"$select.toggle($event)\"></i> <a ng-show=\"$select.allowClear && !$select.isEmpty() && ($select.disabled !== true)\" aria-label=\"{{ $select.baseTitle }} clear\" style=\"margin-right: 10px\" ng-click=\"$select.clear($event)\" class=\"btn btn-xs btn-link pull-right\"><i class=\"glyphicon glyphicon-remove\" aria-hidden=\"true\"></i></a></span></div>");
  2054. $templateCache.put("bootstrap/no-choice.tpl.html","<ul class=\"ui-select-no-choice dropdown-menu\" ng-show=\"$select.items.length == 0\"><li ng-transclude=\"\"></li></ul>");
  2055. $templateCache.put("bootstrap/select-multiple.tpl.html","<div class=\"ui-select-container ui-select-multiple ui-select-bootstrap dropdown form-control\" ng-class=\"{open: $select.open}\"><div><div class=\"ui-select-match\"></div><input type=\"search\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" class=\"ui-select-search input-xs\" placeholder=\"{{$selectMultiple.getPlaceholder()}}\" ng-disabled=\"$select.disabled\" ng-click=\"$select.activate()\" ng-model=\"$select.search\" role=\"combobox\" aria-expanded=\"{{$select.open}}\" aria-label=\"{{$select.baseTitle}}\" ng-class=\"{\'spinner\': $select.refreshing}\" ondrop=\"return false;\"></div><div class=\"ui-select-choices\"></div><div class=\"ui-select-no-choice\"></div></div>");
  2056. $templateCache.put("bootstrap/select.tpl.html","<div class=\"ui-select-container ui-select-bootstrap dropdown\" ng-class=\"{open: $select.open}\"><div class=\"ui-select-match\"></div><span ng-show=\"$select.open && $select.refreshing && $select.spinnerEnabled\" class=\"ui-select-refreshing {{$select.spinnerClass}}\"></span> <input type=\"search\" autocomplete=\"off\" tabindex=\"-1\" aria-expanded=\"true\" aria-label=\"{{ $select.baseTitle }}\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" class=\"form-control ui-select-search\" ng-class=\"{ \'ui-select-search-hidden\' : !$select.searchEnabled }\" placeholder=\"{{$select.placeholder}}\" ng-model=\"$select.search\" ng-show=\"$select.open\"><div class=\"ui-select-choices\"></div><div class=\"ui-select-no-choice\"></div></div>");
  2057. $templateCache.put("select2/choices.tpl.html","<ul tabindex=\"-1\" class=\"ui-select-choices ui-select-choices-content select2-results\"><li class=\"ui-select-choices-group\" ng-class=\"{\'select2-result-with-children\': $select.choiceGrouped($group) }\"><div ng-show=\"$select.choiceGrouped($group)\" class=\"ui-select-choices-group-label select2-result-label\" ng-bind=\"$group.name\"></div><ul id=\"ui-select-choices-{{ $select.generatedId }}\" ng-class=\"{\'select2-result-sub\': $select.choiceGrouped($group), \'select2-result-single\': !$select.choiceGrouped($group) }\"><li role=\"option\" ng-attr-id=\"ui-select-choices-row-{{ $select.generatedId }}-{{$index}}\" class=\"ui-select-choices-row\" ng-class=\"{\'select2-highlighted\': $select.isActive(this), \'select2-disabled\': $select.isDisabled(this)}\"><div class=\"select2-result-label ui-select-choices-row-inner\"></div></li></ul></li></ul>");
  2058. $templateCache.put("select2/match-multiple.tpl.html","<span class=\"ui-select-match\"><li class=\"ui-select-match-item select2-search-choice\" ng-repeat=\"$item in $select.selected track by $index\" ng-class=\"{\'select2-search-choice-focus\':$selectMultiple.activeMatchIndex === $index, \'select2-locked\':$select.isLocked(this, $index)}\" ui-select-sort=\"$select.selected\"><span uis-transclude-append=\"\"></span> <a href=\"javascript:;\" class=\"ui-select-match-close select2-search-choice-close\" ng-click=\"$selectMultiple.removeChoice($index)\" tabindex=\"-1\"></a></li></span>");
  2059. $templateCache.put("select2/match.tpl.html","<a class=\"select2-choice ui-select-match\" ng-class=\"{\'select2-default\': $select.isEmpty()}\" ng-click=\"$select.toggle($event)\" aria-label=\"{{ $select.baseTitle }} select\"><span ng-show=\"$select.isEmpty()\" class=\"select2-chosen\">{{$select.placeholder}}</span> <span ng-hide=\"$select.isEmpty()\" class=\"select2-chosen\" ng-transclude=\"\"></span> <abbr ng-if=\"$select.allowClear && !$select.isEmpty()\" class=\"select2-search-choice-close\" ng-click=\"$select.clear($event)\"></abbr> <span class=\"select2-arrow ui-select-toggle\"><b></b></span></a>");
  2060. $templateCache.put("select2/no-choice.tpl.html","<div class=\"ui-select-no-choice dropdown\" ng-show=\"$select.items.length == 0\"><div class=\"dropdown-content\"><div data-selectable=\"\" ng-transclude=\"\"></div></div></div>");
  2061. $templateCache.put("select2/select-multiple.tpl.html","<div class=\"ui-select-container ui-select-multiple select2 select2-container select2-container-multi\" ng-class=\"{\'select2-container-active select2-dropdown-open open\': $select.open, \'select2-container-disabled\': $select.disabled}\"><ul class=\"select2-choices\"><span class=\"ui-select-match\"></span><li class=\"select2-search-field\"><input type=\"search\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" role=\"combobox\" aria-expanded=\"true\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" aria-label=\"{{ $select.baseTitle }}\" aria-activedescendant=\"ui-select-choices-row-{{ $select.generatedId }}-{{ $select.activeIndex }}\" class=\"select2-input ui-select-search\" placeholder=\"{{$selectMultiple.getPlaceholder()}}\" ng-disabled=\"$select.disabled\" ng-hide=\"$select.disabled\" ng-model=\"$select.search\" ng-click=\"$select.activate()\" style=\"width: 34px;\" ondrop=\"return false;\"></li></ul><div class=\"ui-select-dropdown select2-drop select2-with-searchbox select2-drop-active\" ng-class=\"{\'select2-display-none\': !$select.open || $select.items.length === 0}\"><div class=\"ui-select-choices\"></div></div></div>");
  2062. $templateCache.put("select2/select.tpl.html","<div class=\"ui-select-container select2 select2-container\" ng-class=\"{\'select2-container-active select2-dropdown-open open\': $select.open, \'select2-container-disabled\': $select.disabled, \'select2-container-active\': $select.focus, \'select2-allowclear\': $select.allowClear && !$select.isEmpty()}\"><div class=\"ui-select-match\"></div><div class=\"ui-select-dropdown select2-drop select2-with-searchbox select2-drop-active\" ng-class=\"{\'select2-display-none\': !$select.open}\"><div class=\"search-container\" ng-class=\"{\'ui-select-search-hidden\':!$select.searchEnabled, \'select2-search\':$select.searchEnabled}\"><input type=\"search\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" ng-class=\"{\'select2-active\': $select.refreshing}\" role=\"combobox\" aria-expanded=\"true\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" aria-label=\"{{ $select.baseTitle }}\" class=\"ui-select-search select2-input\" ng-model=\"$select.search\"></div><div class=\"ui-select-choices\"></div><div class=\"ui-select-no-choice\"></div></div></div>");
  2063. $templateCache.put("selectize/choices.tpl.html","<div ng-show=\"$select.open\" class=\"ui-select-choices ui-select-dropdown selectize-dropdown\" ng-class=\"{\'single\': !$select.multiple, \'multi\': $select.multiple}\"><div class=\"ui-select-choices-content selectize-dropdown-content\"><div class=\"ui-select-choices-group optgroup\"><div ng-show=\"$select.isGrouped\" class=\"ui-select-choices-group-label optgroup-header\" ng-bind=\"$group.name\"></div><div role=\"option\" class=\"ui-select-choices-row\" ng-class=\"{active: $select.isActive(this), disabled: $select.isDisabled(this)}\"><div class=\"option ui-select-choices-row-inner\" data-selectable=\"\"></div></div></div></div></div>");
  2064. $templateCache.put("selectize/match-multiple.tpl.html","<div class=\"ui-select-match\" data-value=\"\" ng-repeat=\"$item in $select.selected track by $index\" ng-click=\"$selectMultiple.activeMatchIndex = $index;\" ng-class=\"{\'active\':$selectMultiple.activeMatchIndex === $index}\" ui-select-sort=\"$select.selected\"><span class=\"ui-select-match-item\" ng-class=\"{\'select-locked\':$select.isLocked(this, $index)}\"><span uis-transclude-append=\"\"></span> <span class=\"remove ui-select-match-close\" ng-hide=\"$select.disabled\" ng-click=\"$selectMultiple.removeChoice($index)\">&times;</span></span></div>");
  2065. $templateCache.put("selectize/match.tpl.html","<div ng-hide=\"$select.searchEnabled && ($select.open || $select.isEmpty())\" class=\"ui-select-match\"><span ng-show=\"!$select.searchEnabled && ($select.isEmpty() || $select.open)\" class=\"ui-select-placeholder text-muted\">{{$select.placeholder}}</span> <span ng-hide=\"$select.isEmpty() || $select.open\" ng-transclude=\"\"></span></div>");
  2066. $templateCache.put("selectize/no-choice.tpl.html","<div class=\"ui-select-no-choice selectize-dropdown\" ng-show=\"$select.items.length == 0\"><div class=\"selectize-dropdown-content\"><div data-selectable=\"\" ng-transclude=\"\"></div></div></div>");
  2067. $templateCache.put("selectize/select-multiple.tpl.html","<div class=\"ui-select-container selectize-control multi plugin-remove_button\" ng-class=\"{\'open\': $select.open}\"><div class=\"selectize-input\" ng-class=\"{\'focus\': $select.open, \'disabled\': $select.disabled, \'selectize-focus\' : $select.focus}\" ng-click=\"$select.open && !$select.searchEnabled ? $select.toggle($event) : $select.activate()\"><div class=\"ui-select-match\"></div><input type=\"search\" autocomplete=\"off\" tabindex=\"-1\" class=\"ui-select-search\" ng-class=\"{\'ui-select-search-hidden\':!$select.searchEnabled}\" placeholder=\"{{$selectMultiple.getPlaceholder()}}\" ng-model=\"$select.search\" ng-disabled=\"$select.disabled\" aria-expanded=\"{{$select.open}}\" aria-label=\"{{ $select.baseTitle }}\" ondrop=\"return false;\"></div><div class=\"ui-select-choices\"></div><div class=\"ui-select-no-choice\"></div></div>");
  2068. $templateCache.put("selectize/select.tpl.html","<div class=\"ui-select-container selectize-control single\" ng-class=\"{\'open\': $select.open}\"><div class=\"selectize-input\" ng-class=\"{\'focus\': $select.open, \'disabled\': $select.disabled, \'selectize-focus\' : $select.focus}\" ng-click=\"$select.open && !$select.searchEnabled ? $select.toggle($event) : $select.activate()\"><div class=\"ui-select-match\"></div><input type=\"search\" autocomplete=\"off\" tabindex=\"-1\" class=\"ui-select-search ui-select-toggle\" ng-class=\"{\'ui-select-search-hidden\':!$select.searchEnabled}\" ng-click=\"$select.toggle($event)\" placeholder=\"{{$select.placeholder}}\" ng-model=\"$select.search\" ng-hide=\"!$select.isEmpty() && !$select.open\" ng-disabled=\"$select.disabled\" aria-label=\"{{ $select.baseTitle }}\"></div><div class=\"ui-select-choices\"></div><div class=\"ui-select-no-choice\"></div></div>");}]);