PageSourceSearch

https://www.imglobal.com/ResourcePackages/IMG/MyIMGWidgets/select.js?package=IMG&version=2026-9-29-19-36-16

js imglobal.com collected 2026-10-02 14:45:06 UTC 100,655 bytes, 2,427 lines download raw bytes

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

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.