3 * http://github.com/angular-ui/ui-select
4 * Version: 0.11.2 - 2015-03-17T04:08:46.474Z
32 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 : "'"
35 isControl: function (e) {
45 if (e.metaKey) return true;
49 isFunctionKey: function (k) {
50 k = k.which ? k.which : k;
51 return k >= 112 && k <= 123;
53 isVerticalMovement: function (k){
54 return ~[KEY.UP, KEY.DOWN].indexOf(k);
56 isHorizontalMovement: function (k){
57 return ~[KEY.LEFT,KEY.RIGHT,KEY.BACKSPACE,KEY.DELETE].indexOf(k);
62 * Add querySelectorAll() to jqLite.
64 * jqLite find() is limited to lookups by tag name.
65 * TODO This will change with future versions of AngularJS, to be removed when this happens
67 * See jqLite.find - why not use querySelectorAll? https://github.com/angular/angular.js/issues/3586
68 * See feat(jqLite): use querySelectorAll instead of getElementsByTagName in jqLite.find https://github.com/angular/angular.js/pull/3598
70 if (angular.element.prototype.querySelectorAll === undefined) {
71 angular.element.prototype.querySelectorAll = function(selector) {
72 return angular.element(this[0].querySelectorAll(selector));
77 * Add closest() to jqLite.
79 if (angular.element.prototype.closest === undefined) {
80 angular.element.prototype.closest = function( selector) {
82 var matchesSelector = elem.matches || elem.webkitMatchesSelector || elem.mozMatchesSelector || elem.msMatchesSelector;
85 if (matchesSelector.bind(elem)(selector)) {
88 elem = elem.parentElement;
97 var uis = angular.module('ui.select', [])
99 .constant('uiSelectConfig', {
103 placeholder: '', // Empty by default, like HTML tag <select>
104 refreshDelay: 1000, // In milliseconds
106 generateId: function() {
112 // See Rename minErr and make it accessible from outside https://github.com/angular/angular.js/issues/6913
113 .service('uiSelectMinErr', function() {
114 var minErr = angular.$$minErr('ui.select');
116 var error = minErr.apply(this, arguments);
117 var message = error.message.replace(new RegExp('\nhttp://errors.angularjs.org/.*'), '');
118 return new Error(message);
122 // Recreates old behavior of ng-transclude. Used internally.
123 .directive('uisTranscludeAppend', function () {
125 link: function (scope, element, attrs, ctrl, transclude) {
126 transclude(scope, function (clone) {
127 element.append(clone);
134 * Highlights text that matches $select.search.
136 * Taken from AngularUI Bootstrap Typeahead
137 * See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L340
139 .filter('highlight', function() {
140 function escapeRegexp(queryToEscape) {
141 return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
144 return function(matchItem, query) {
145 return query && matchItem ? matchItem.replace(new RegExp(escapeRegexp(query), 'gi'), '<span class="ui-select-highlight">$&</span>') : matchItem;
150 * A read-only equivalent of jQuery's offset function: http://api.jquery.com/offset/
152 * Taken from AngularUI Bootstrap Position:
153 * See https://github.com/angular-ui/bootstrap/blob/master/src/position/position.js#L70
155 .factory('uisOffset',
156 ['$document', '$window',
157 function ($document, $window) {
159 return function(element) {
160 var boundingClientRect = element[0].getBoundingClientRect();
162 width: boundingClientRect.width || element.prop('offsetWidth'),
163 height: boundingClientRect.height || element.prop('offsetHeight'),
164 top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),
165 left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)
170 uis.directive('uiSelectChoices',
171 ['uiSelectConfig', 'uisRepeatParser', 'uiSelectMinErr', '$compile',
172 function(uiSelectConfig, RepeatParser, uiSelectMinErr, $compile) {
176 require: '^uiSelect',
179 templateUrl: function(tElement) {
180 // Gets theme attribute from parent (ui-select)
181 var theme = tElement.parent().attr('theme') || uiSelectConfig.theme;
182 return theme + '/choices.tpl.html';
185 compile: function(tElement, tAttrs) {
187 if (!tAttrs.repeat) throw uiSelectMinErr('repeat', "Expected 'repeat' expression.");
189 return function link(scope, element, attrs, $select, transcludeFn) {
191 // var repeat = RepeatParser.parse(attrs.repeat);
192 var groupByExp = attrs.groupBy;
194 $select.parseRepeatAttr(attrs.repeat, groupByExp); //Result ready at $select.parserResult
196 $select.disableChoiceExpression = attrs.uiDisableChoice;
197 $select.onHighlightCallback = attrs.onHighlight;
200 var groups = element.querySelectorAll('.ui-select-choices-group');
201 if (groups.length !== 1) throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-group but got '{0}'.", groups.length);
202 groups.attr('ng-repeat', RepeatParser.getGroupNgRepeatExpression());
205 var choices = element.querySelectorAll('.ui-select-choices-row');
206 if (choices.length !== 1) {
207 throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row but got '{0}'.", choices.length);
210 choices.attr('ng-repeat', RepeatParser.getNgRepeatExpression($select.parserResult.itemName, '$select.items', $select.parserResult.trackByExp, groupByExp))
211 .attr('ng-if', '$select.open') //Prevent unnecessary watches when dropdown is closed
212 .attr('ng-mouseenter', '$select.setActiveItem('+$select.parserResult.itemName +')')
213 .attr('ng-click', '$select.select(' + $select.parserResult.itemName + ',false,$event)');
215 var rowsInner = element.querySelectorAll('.ui-select-choices-row-inner');
216 if (rowsInner.length !== 1) throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row-inner but got '{0}'.", rowsInner.length);
217 rowsInner.attr('uis-transclude-append', ''); //Adding uisTranscludeAppend directive to row element after choices element has ngRepeat
219 $compile(element, transcludeFn)(scope); //Passing current transcludeFn to be able to append elements correctly from uisTranscludeAppend
221 scope.$watch('$select.search', function(newValue) {
222 if(newValue && !$select.open && $select.multiple) $select.activate(false, true);
223 $select.activeIndex = $select.tagging.isActivated ? -1 : 0;
224 $select.refresh(attrs.refresh);
227 attrs.$observe('refreshDelay', function() {
228 // $eval() is needed otherwise we get a string instead of a number
229 var refreshDelay = scope.$eval(attrs.refreshDelay);
230 $select.refreshDelay = refreshDelay !== undefined ? refreshDelay : uiSelectConfig.refreshDelay;
238 * Contains ui-select "intelligence".
240 * The goal is to limit dependency on the DOM whenever possible and
241 * put as much logic in the controller (instead of the link functions) as possible so it can be easily tested.
243 uis.controller('uiSelectCtrl',
244 ['$scope', '$element', '$timeout', '$filter', 'uisRepeatParser', 'uiSelectMinErr', 'uiSelectConfig',
245 function($scope, $element, $timeout, $filter, RepeatParser, uiSelectMinErr, uiSelectConfig) {
249 var EMPTY_SEARCH = '';
251 ctrl.placeholder = uiSelectConfig.placeholder;
252 ctrl.searchEnabled = uiSelectConfig.searchEnabled;
253 ctrl.sortable = uiSelectConfig.sortable;
254 ctrl.refreshDelay = uiSelectConfig.refreshDelay;
256 ctrl.removeSelected = false; //If selected item(s) should be removed from dropdown list
257 ctrl.closeOnSelect = true; //Initialized inside uiSelect directive link function
258 ctrl.search = EMPTY_SEARCH;
260 ctrl.activeIndex = 0; //Dropdown of choices
261 ctrl.items = []; //All available choices
265 ctrl.disabled = false;
266 ctrl.selected = undefined;
268 ctrl.focusser = undefined; //Reference to input element used to handle focus events
269 ctrl.resetSearchInput = true;
270 ctrl.multiple = undefined; // Initialized inside uiSelect directive link function
271 ctrl.disableChoiceExpression = undefined; // Initialized inside uiSelectChoices directive link function
272 ctrl.tagging = {isActivated: false, fct: undefined};
273 ctrl.taggingTokens = {isActivated: false, tokens: undefined};
274 ctrl.lockChoiceExpression = undefined; // Initialized inside uiSelectMatch directive link function
275 ctrl.clickTriggeredSelect = false;
276 ctrl.$filter = $filter;
278 ctrl.searchInput = $element.querySelectorAll('input.ui-select-search');
279 if (ctrl.searchInput.length !== 1) {
280 throw uiSelectMinErr('searchInput', "Expected 1 input.ui-select-search but got '{0}'.", ctrl.searchInput.length);
283 ctrl.isEmpty = function() {
284 return angular.isUndefined(ctrl.selected) || ctrl.selected === null || ctrl.selected === '';
287 // Most of the time the user does not want to empty the search input when in typeahead mode
288 function _resetSearchInput() {
289 if (ctrl.resetSearchInput || (ctrl.resetSearchInput === undefined && uiSelectConfig.resetSearchInput)) {
290 ctrl.search = EMPTY_SEARCH;
292 if (ctrl.selected && ctrl.items.length && !ctrl.multiple) {
293 ctrl.activeIndex = ctrl.items.indexOf(ctrl.selected);
298 // When the user clicks on ui-select, displays the dropdown list
299 ctrl.activate = function(initSearchValue, avoidReset) {
300 if (!ctrl.disabled && !ctrl.open) {
301 if(!avoidReset) _resetSearchInput();
303 $scope.$broadcast('uis:activate');
307 ctrl.activeIndex = ctrl.activeIndex >= ctrl.items.length ? 0 : ctrl.activeIndex;
309 // ensure that the index is set to zero for tagging variants
310 // that where first option is auto-selected
311 if ( ctrl.activeIndex === -1 && ctrl.taggingLabel !== false ) {
312 ctrl.activeIndex = 0;
315 // Give it time to appear before focus
316 $timeout(function() {
317 ctrl.search = initSearchValue || ctrl.search;
318 ctrl.searchInput[0].focus();
323 ctrl.findGroupByName = function(name) {
324 return ctrl.groups && ctrl.groups.filter(function(group) {
325 return group.name === name;
329 ctrl.parseRepeatAttr = function(repeatAttr, groupByExp) {
330 function updateGroups(items) {
332 angular.forEach(items, function(item) {
333 var groupFn = $scope.$eval(groupByExp);
334 var groupName = angular.isFunction(groupFn) ? groupFn(item) : item[groupFn];
335 var group = ctrl.findGroupByName(groupName);
337 group.items.push(item);
340 ctrl.groups.push({name: groupName, items: [item]});
344 ctrl.groups.forEach(function(group) {
345 ctrl.items = ctrl.items.concat(group.items);
349 function setPlainItems(items) {
353 ctrl.setItemsFn = groupByExp ? updateGroups : setPlainItems;
355 ctrl.parserResult = RepeatParser.parse(repeatAttr);
357 ctrl.isGrouped = !!groupByExp;
358 ctrl.itemProperty = ctrl.parserResult.itemName;
360 ctrl.refreshItems = function (data){
361 data = data || ctrl.parserResult.source($scope);
362 var selectedItems = ctrl.selected;
363 //TODO should implement for single mode removeSelected
364 if ((angular.isArray(selectedItems) && !selectedItems.length) || !ctrl.removeSelected) {
365 ctrl.setItemsFn(data);
367 if ( data !== undefined ) {
368 var filteredItems = data.filter(function(i) {return selectedItems.indexOf(i) < 0;});
369 ctrl.setItemsFn(filteredItems);
374 // See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L259
375 $scope.$watchCollection(ctrl.parserResult.source, function(items) {
376 if (items === undefined || items === null) {
377 // If the user specifies undefined or null => reset the collection
378 // Special case: items can be undefined if the user did not initialized the collection on the scope
379 // i.e $scope.addresses = [] is missing
382 if (!angular.isArray(items)) {
383 throw uiSelectMinErr('items', "Expected an array but got '{0}'.", items);
385 //Remove already selected items (ex: while searching)
386 //TODO Should add a test
387 ctrl.refreshItems(items);
388 ctrl.ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters
395 var _refreshDelayPromise;
398 * Typeahead mode: lets the user refresh the collection using his own function.
400 * See Expose $select.search for external / remote filtering https://github.com/angular-ui/ui-select/pull/31
402 ctrl.refresh = function(refreshAttr) {
403 if (refreshAttr !== undefined) {
406 // See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L155
407 // FYI AngularStrap typeahead does not have debouncing: https://github.com/mgcrea/angular-strap/blob/v2.0.0-rc.4/src/typeahead/typeahead.js#L177
408 if (_refreshDelayPromise) {
409 $timeout.cancel(_refreshDelayPromise);
411 _refreshDelayPromise = $timeout(function() {
412 $scope.$eval(refreshAttr);
413 }, ctrl.refreshDelay);
417 ctrl.setActiveItem = function(item) {
418 ctrl.activeIndex = ctrl.items.indexOf(item);
421 ctrl.isActive = function(itemScope) {
425 var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]);
426 var isActive = itemIndex === ctrl.activeIndex;
428 if ( !isActive || ( itemIndex < 0 && ctrl.taggingLabel !== false ) ||( itemIndex < 0 && ctrl.taggingLabel === false) ) {
432 if (isActive && !angular.isUndefined(ctrl.onHighlightCallback)) {
433 itemScope.$eval(ctrl.onHighlightCallback);
439 ctrl.isDisabled = function(itemScope) {
441 if (!ctrl.open) return;
443 var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]);
444 var isDisabled = false;
447 if (itemIndex >= 0 && !angular.isUndefined(ctrl.disableChoiceExpression)) {
448 item = ctrl.items[itemIndex];
449 isDisabled = !!(itemScope.$eval(ctrl.disableChoiceExpression)); // force the boolean value
450 item._uiSelectChoiceDisabled = isDisabled; // store this for later reference
457 // When the user selects an item with ENTER or clicks the dropdown
458 ctrl.select = function(item, skipFocusser, $event) {
459 if (item === undefined || !item._uiSelectChoiceDisabled) {
461 if ( ! ctrl.items && ! ctrl.search ) return;
463 if (!item || !item._uiSelectChoiceDisabled) {
464 if(ctrl.tagging.isActivated) {
465 // if taggingLabel is disabled, we pull from ctrl.search val
466 if ( ctrl.taggingLabel === false ) {
467 if ( ctrl.activeIndex < 0 ) {
468 item = ctrl.tagging.fct !== undefined ? ctrl.tagging.fct(ctrl.search) : ctrl.search;
469 if (!item || angular.equals( ctrl.items[0], item ) ) {
473 // keyboard nav happened first, user selected from dropdown
474 item = ctrl.items[ctrl.activeIndex];
477 // tagging always operates at index zero, taggingLabel === false pushes
478 // the ctrl.search value without having it injected
479 if ( ctrl.activeIndex === 0 ) {
480 // ctrl.tagging pushes items to ctrl.items, so we only have empty val
481 // for `item` if it is a detected duplicate
482 if ( item === undefined ) return;
484 // create new item on the fly if we don't already have one;
485 // use tagging function if we have one
486 if ( ctrl.tagging.fct !== undefined && typeof item === 'string' ) {
487 item = ctrl.tagging.fct(ctrl.search);
489 // if item type is 'string', apply the tagging label
490 } else if ( typeof item === 'string' ) {
491 // trim the trailing space
492 item = item.replace(ctrl.taggingLabel,'').trim();
496 // search ctrl.selected for dupes potentially caused by tagging and return early if found
497 if ( ctrl.selected && angular.isArray(ctrl.selected) && ctrl.selected.filter( function (selection) { return angular.equals(selection, item); }).length > 0 ) {
498 ctrl.close(skipFocusser);
503 $scope.$broadcast('uis:select', item);
506 locals[ctrl.parserResult.itemName] = item;
509 ctrl.onSelectCallback($scope, {
511 $model: ctrl.parserResult.modelMapper($scope, locals)
515 if (ctrl.closeOnSelect) {
516 ctrl.close(skipFocusser);
518 if ($event && $event.type === 'click') {
519 ctrl.clickTriggeredSelect = true;
525 // Closes the dropdown
526 ctrl.close = function(skipFocusser) {
527 if (!ctrl.open) return;
528 if (ctrl.ngModel && ctrl.ngModel.$setTouched) ctrl.ngModel.$setTouched();
532 $scope.$broadcast('uis:close', skipFocusser);
536 ctrl.setFocus = function(){
537 if (!ctrl.focus) ctrl.focusInput[0].focus();
540 ctrl.clear = function($event) {
541 ctrl.select(undefined);
542 $event.stopPropagation();
543 ctrl.focusser[0].focus();
547 ctrl.toggle = function(e) {
557 ctrl.isLocked = function(itemScope, itemIndex) {
558 var isLocked, item = ctrl.selected[itemIndex];
560 if (item && !angular.isUndefined(ctrl.lockChoiceExpression)) {
561 isLocked = !!(itemScope.$eval(ctrl.lockChoiceExpression)); // force the boolean value
562 item._uiSelectChoiceLocked = isLocked; // store this for later reference
568 var sizeWatch = null;
569 ctrl.sizeSearchInput = function() {
571 var input = ctrl.searchInput[0],
572 container = ctrl.searchInput.parent().parent()[0],
573 calculateContainerWidth = function() {
574 // Return the container width only if the search input is visible
575 return container.clientWidth * !!input.offsetParent;
577 updateIfVisible = function(containerWidth) {
578 if (containerWidth === 0) {
581 var inputWidth = containerWidth - input.offsetLeft - 10;
582 if (inputWidth < 50) inputWidth = containerWidth;
583 ctrl.searchInput.css('width', inputWidth+'px');
587 ctrl.searchInput.css('width', '10px');
588 $timeout(function() { //Give tags time to render correctly
589 if (sizeWatch === null && !updateIfVisible(calculateContainerWidth())) {
590 sizeWatch = $scope.$watch(calculateContainerWidth, function(containerWidth) {
591 if (updateIfVisible(containerWidth)) {
600 function _handleDropDownSelection(key) {
601 var processed = true;
604 if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode
605 else if (ctrl.activeIndex < ctrl.items.length - 1) { ctrl.activeIndex++; }
608 if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode
609 else if (ctrl.activeIndex > 0 || (ctrl.search.length === 0 && ctrl.tagging.isActivated && ctrl.activeIndex > -1)) { ctrl.activeIndex--; }
612 if (!ctrl.multiple || ctrl.open) ctrl.select(ctrl.items[ctrl.activeIndex], true);
615 if(ctrl.open && ctrl.activeIndex >= 0){
616 ctrl.select(ctrl.items[ctrl.activeIndex]); // Make sure at least one dropdown item is highlighted before adding.
618 ctrl.activate(false, true); //In case its the search input in 'multiple' mode
630 // Bind to keyboard shortcuts
631 ctrl.searchInput.on('keydown', function(e) {
635 // if(~[KEY.ESC,KEY.TAB].indexOf(key)){
640 $scope.$apply(function() {
644 if (ctrl.items.length > 0 || ctrl.tagging.isActivated) {
645 _handleDropDownSelection(key);
646 if ( ctrl.taggingTokens.isActivated ) {
647 for (var i = 0; i < ctrl.taggingTokens.tokens.length; i++) {
648 if ( ctrl.taggingTokens.tokens[i] === KEY.MAP[e.keyCode] ) {
649 // make sure there is a new value to push via tagging
650 if ( ctrl.search.length > 0 ) {
656 $timeout(function() {
657 ctrl.searchInput.triggerHandler('tagged');
658 var newItem = ctrl.search.replace(KEY.MAP[e.keyCode],'').trim();
659 if ( ctrl.tagging.fct ) {
660 newItem = ctrl.tagging.fct( newItem );
662 if (newItem) ctrl.select(newItem, true);
670 if(KEY.isVerticalMovement(key) && ctrl.items.length > 0){
671 _ensureHighlightVisible();
676 // If tagging try to split by tokens and add items
677 ctrl.searchInput.on('paste', function (e) {
678 var data = e.originalEvent.clipboardData.getData('text/plain');
679 if (data && data.length > 0 && ctrl.taggingTokens.isActivated && ctrl.tagging.fct) {
680 var items = data.split(ctrl.taggingTokens.tokens[0]); // split by first token only
681 if (items && items.length > 0) {
682 angular.forEach(items, function (item) {
683 var newItem = ctrl.tagging.fct(item);
685 ctrl.select(newItem, true);
694 ctrl.searchInput.on('tagged', function() {
695 $timeout(function() {
700 // See https://github.com/ivaynberg/select2/blob/3.4.6/select2.js#L1431
701 function _ensureHighlightVisible() {
702 var container = $element.querySelectorAll('.ui-select-choices-content');
703 var choices = container.querySelectorAll('.ui-select-choices-row');
704 if (choices.length < 1) {
705 throw uiSelectMinErr('choices', "Expected multiple .ui-select-choices-row but got '{0}'.", choices.length);
708 if (ctrl.activeIndex < 0) {
712 var highlighted = choices[ctrl.activeIndex];
713 var posY = highlighted.offsetTop + highlighted.clientHeight - container[0].scrollTop;
714 var height = container[0].offsetHeight;
717 container[0].scrollTop += posY - height;
718 } else if (posY < highlighted.clientHeight) {
719 if (ctrl.isGrouped && ctrl.activeIndex === 0)
720 container[0].scrollTop = 0; //To make group header visible when going all the way up
722 container[0].scrollTop -= highlighted.clientHeight - posY;
726 $scope.$on('$destroy', function() {
727 ctrl.searchInput.off('keyup keydown tagged blur paste');
732 uis.directive('uiSelect',
733 ['$document', 'uiSelectConfig', 'uiSelectMinErr', 'uisOffset', '$compile', '$parse', '$timeout',
734 function($document, uiSelectConfig, uiSelectMinErr, uisOffset, $compile, $parse, $timeout) {
738 templateUrl: function(tElement, tAttrs) {
739 var theme = tAttrs.theme || uiSelectConfig.theme;
740 return theme + (angular.isDefined(tAttrs.multiple) ? '/select-multiple.tpl.html' : '/select.tpl.html');
744 require: ['uiSelect', '^ngModel'],
747 controller: 'uiSelectCtrl',
748 controllerAs: '$select',
749 compile: function(tElement, tAttrs) {
751 //Multiple or Single depending if multiple attribute presence
752 if (angular.isDefined(tAttrs.multiple))
753 tElement.append("<ui-select-multiple/>").removeAttr('multiple');
755 tElement.append("<ui-select-single/>");
757 return function(scope, element, attrs, ctrls, transcludeFn) {
759 var $select = ctrls[0];
760 var ngModel = ctrls[1];
762 $select.generatedId = uiSelectConfig.generateId();
763 $select.baseTitle = attrs.title || 'Select box';
764 $select.focusserTitle = $select.baseTitle + ' focus';
765 $select.focusserId = 'focusser-' + $select.generatedId;
767 $select.closeOnSelect = function() {
768 if (angular.isDefined(attrs.closeOnSelect)) {
769 return $parse(attrs.closeOnSelect)();
771 return uiSelectConfig.closeOnSelect;
775 $select.onSelectCallback = $parse(attrs.onSelect);
776 $select.onRemoveCallback = $parse(attrs.onRemove);
778 //Set reference to ngModel from uiSelectCtrl
779 $select.ngModel = ngModel;
781 $select.choiceGrouped = function(group){
782 return $select.isGrouped && group && group.name;
786 attrs.$observe('tabindex', function(value) {
787 $select.focusInput.attr("tabindex", value);
788 element.removeAttr("tabindex");
792 scope.$watch('searchEnabled', function() {
793 var searchEnabled = scope.$eval(attrs.searchEnabled);
794 $select.searchEnabled = searchEnabled !== undefined ? searchEnabled : uiSelectConfig.searchEnabled;
797 scope.$watch('sortable', function() {
798 var sortable = scope.$eval(attrs.sortable);
799 $select.sortable = sortable !== undefined ? sortable : uiSelectConfig.sortable;
802 attrs.$observe('disabled', function() {
803 // No need to use $eval() (thanks to ng-disabled) since we already get a boolean instead of a string
804 $select.disabled = attrs.disabled !== undefined ? attrs.disabled : false;
807 attrs.$observe('resetSearchInput', function() {
808 // $eval() is needed otherwise we get a string instead of a boolean
809 var resetSearchInput = scope.$eval(attrs.resetSearchInput);
810 $select.resetSearchInput = resetSearchInput !== undefined ? resetSearchInput : true;
813 attrs.$observe('tagging', function() {
814 if(attrs.tagging !== undefined)
816 // $eval() is needed otherwise we get a string instead of a boolean
817 var taggingEval = scope.$eval(attrs.tagging);
818 $select.tagging = {isActivated: true, fct: taggingEval !== true ? taggingEval : undefined};
822 $select.tagging = {isActivated: false, fct: undefined};
826 attrs.$observe('taggingLabel', function() {
827 if(attrs.tagging !== undefined )
829 // check eval for FALSE, in this case, we disable the labels
830 // associated with tagging
831 if ( attrs.taggingLabel === 'false' ) {
832 $select.taggingLabel = false;
836 $select.taggingLabel = attrs.taggingLabel !== undefined ? attrs.taggingLabel : '(new)';
841 attrs.$observe('taggingTokens', function() {
842 if (attrs.tagging !== undefined) {
843 var tokens = attrs.taggingTokens !== undefined ? attrs.taggingTokens.split('|') : [',','ENTER'];
844 $select.taggingTokens = {isActivated: true, tokens: tokens };
848 //Automatically gets focus when loaded
849 if (angular.isDefined(attrs.autofocus)){
855 //Gets focus based on scope event name (e.g. focus-on='SomeEventName')
856 if (angular.isDefined(attrs.focusOn)){
857 scope.$on(attrs.focusOn, function() {
864 function onDocumentClick(e) {
865 if (!$select.open) return; //Skip it if dropdown is close
867 var contains = false;
870 // Firefox 3.6 does not support element.contains()
871 // See Node.contains https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
872 contains = window.jQuery.contains(element[0], e.target);
874 contains = element[0].contains(e.target);
877 if (!contains && !$select.clickTriggeredSelect) {
878 //Will lose focus only with certain targets
879 var focusableControls = ['input','button','textarea'];
880 var targetScope = angular.element(e.target).scope(); //To check if target is other ui-select
881 var skipFocusser = targetScope && targetScope.$select && targetScope.$select !== $select; //To check if target is other ui-select
882 if (!skipFocusser) skipFocusser = ~focusableControls.indexOf(e.target.tagName.toLowerCase()); //Check if target is input, button or textarea
883 $select.close(skipFocusser);
886 $select.clickTriggeredSelect = false;
889 // See Click everywhere but here event http://stackoverflow.com/questions/12931369
890 $document.on('click', onDocumentClick);
892 scope.$on('$destroy', function() {
893 $document.off('click', onDocumentClick);
896 // Move transcluded elements to their correct position in main template
897 transcludeFn(scope, function(clone) {
898 // See Transclude in AngularJS http://blog.omkarpatil.com/2012/11/transclude-in-angularjs.html
900 // One day jqLite will be replaced by jQuery and we will be able to write:
901 // var transcludedElement = clone.filter('.my-class')
902 // instead of creating a hackish DOM element:
903 var transcluded = angular.element('<div>').append(clone);
905 var transcludedMatch = transcluded.querySelectorAll('.ui-select-match');
906 transcludedMatch.removeAttr('ui-select-match'); //To avoid loop in case directive as attr
907 transcludedMatch.removeAttr('data-ui-select-match'); // Properly handle HTML5 data-attributes
908 if (transcludedMatch.length !== 1) {
909 throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-match but got '{0}'.", transcludedMatch.length);
911 element.querySelectorAll('.ui-select-match').replaceWith(transcludedMatch);
913 var transcludedChoices = transcluded.querySelectorAll('.ui-select-choices');
914 transcludedChoices.removeAttr('ui-select-choices'); //To avoid loop in case directive as attr
915 transcludedChoices.removeAttr('data-ui-select-choices'); // Properly handle HTML5 data-attributes
916 if (transcludedChoices.length !== 1) {
917 throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-choices but got '{0}'.", transcludedChoices.length);
919 element.querySelectorAll('.ui-select-choices').replaceWith(transcludedChoices);
922 // Support for appending the select field to the body when its open
923 var appendToBody = scope.$eval(attrs.appendToBody);
924 if (appendToBody !== undefined ? appendToBody : uiSelectConfig.appendToBody) {
925 scope.$watch('$select.open', function(isOpen) {
933 // Move the dropdown back to its original location when the scope is destroyed. Otherwise
934 // it might stick around when the user routes away or the select field is otherwise removed
935 scope.$on('$destroy', function() {
940 // Hold on to a reference to the .ui-select-container element for appendToBody support
941 var placeholder = null,
944 function positionDropdown() {
945 // Remember the absolute position of the element
946 var offset = uisOffset(element);
948 // Clone the element into a placeholder element to take its original place in the DOM
949 placeholder = angular.element('<div class="ui-select-placeholder"></div>');
950 placeholder[0].style.width = offset.width + 'px';
951 placeholder[0].style.height = offset.height + 'px';
952 element.after(placeholder);
954 // Remember the original value of the element width inline style, so it can be restored
955 // when the dropdown is closed
956 originalWidth = element[0].style.width;
958 // Now move the actual dropdown element to the end of the body
959 $document.find('body').append(element);
961 element[0].style.position = 'absolute';
962 element[0].style.left = offset.left + 'px';
963 element[0].style.top = offset.top + 'px';
964 element[0].style.width = offset.width + 'px';
967 function resetDropdown() {
968 if (placeholder === null) {
969 // The dropdown has not actually been display yet, so there's nothing to reset
973 // Move the dropdown element back to its original location in the DOM
974 placeholder.replaceWith(element);
977 element[0].style.position = '';
978 element[0].style.left = '';
979 element[0].style.top = '';
980 element[0].style.width = originalWidth;
987 uis.directive('uiSelectMatch', ['uiSelectConfig', function(uiSelectConfig) {
990 require: '^uiSelect',
993 templateUrl: function(tElement) {
994 // Gets theme attribute from parent (ui-select)
995 var theme = tElement.parent().attr('theme') || uiSelectConfig.theme;
996 var multi = tElement.parent().attr('multiple');
997 return theme + (multi ? '/match-multiple.tpl.html' : '/match.tpl.html');
999 link: function(scope, element, attrs, $select) {
1000 $select.lockChoiceExpression = attrs.uiLockChoice;
1001 attrs.$observe('placeholder', function(placeholder) {
1002 $select.placeholder = placeholder !== undefined ? placeholder : uiSelectConfig.placeholder;
1005 function setAllowClear(allow) {
1006 $select.allowClear = (angular.isDefined(allow)) ? (allow === '') ? true : (allow.toLowerCase() === 'true') : false;
1009 attrs.$observe('allowClear', setAllowClear);
1010 setAllowClear(attrs.allowClear);
1012 if($select.multiple){
1013 $select.sizeSearchInput();
1020 uis.directive('uiSelectMultiple', ['uiSelectMinErr','$timeout', function(uiSelectMinErr, $timeout) {
1023 require: ['^uiSelect', '^ngModel'],
1025 controller: ['$scope','$timeout', function($scope, $timeout){
1028 $select = $scope.$select,
1031 //Wait for link fn to inject it
1032 $scope.$evalAsync(function(){ ngModel = $scope.ngModel; });
1034 ctrl.activeMatchIndex = -1;
1036 ctrl.updateModel = function(){
1037 ngModel.$setViewValue(Date.now()); //Set timestamp as a unique string to force changes
1038 ctrl.refreshComponent();
1041 ctrl.refreshComponent = function(){
1042 //Remove already selected items
1043 //e.g. When user clicks on a selection, the selected array changes and
1044 //the dropdown should remove that item
1045 $select.refreshItems();
1046 $select.sizeSearchInput();
1049 // Remove item from multiple select
1050 ctrl.removeChoice = function(index){
1052 var removedChoice = $select.selected[index];
1054 // if the choice is locked, can't remove it
1055 if(removedChoice._uiSelectChoiceLocked) return;
1058 locals[$select.parserResult.itemName] = removedChoice;
1060 $select.selected.splice(index, 1);
1061 ctrl.activeMatchIndex = -1;
1062 $select.sizeSearchInput();
1064 // Give some time for scope propagation.
1065 $timeout(function(){
1066 $select.onRemoveCallback($scope, {
1067 $item: removedChoice,
1068 $model: $select.parserResult.modelMapper($scope, locals)
1076 ctrl.getPlaceholder = function(){
1078 if($select.selected.length) return;
1079 return $select.placeholder;
1084 controllerAs: '$selectMultiple',
1086 link: function(scope, element, attrs, ctrls) {
1088 var $select = ctrls[0];
1089 var ngModel = scope.ngModel = ctrls[1];
1090 var $selectMultiple = scope.$selectMultiple;
1092 //$select.selected = raw selected objects (ignoring any property binding)
1094 $select.multiple = true;
1095 $select.removeSelected = true;
1097 //Input that will handle focus
1098 $select.focusInput = $select.searchInput;
1100 //From view --> model
1101 ngModel.$parsers.unshift(function () {
1104 resultMultiple = [];
1105 for (var j = $select.selected.length - 1; j >= 0; j--) {
1107 locals[$select.parserResult.itemName] = $select.selected[j];
1108 result = $select.parserResult.modelMapper(scope, locals);
1109 resultMultiple.unshift(result);
1111 return resultMultiple;
1114 // From model --> view
1115 ngModel.$formatters.unshift(function (inputValue) {
1116 var data = $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search
1119 if (!data) return inputValue;
1120 var resultMultiple = [];
1121 var checkFnMultiple = function(list, value){
1122 if (!list || !list.length) return;
1123 for (var p = list.length - 1; p >= 0; p--) {
1124 locals[$select.parserResult.itemName] = list[p];
1125 result = $select.parserResult.modelMapper(scope, locals);
1126 if($select.parserResult.trackByExp){
1127 var matches = /\.(.+)/.exec($select.parserResult.trackByExp);
1128 if(matches.length>0 && result[matches[1]] == value[matches[1]]){
1129 resultMultiple.unshift(list[p]);
1133 if (angular.equals(result,value)){
1134 resultMultiple.unshift(list[p]);
1140 if (!inputValue) return resultMultiple; //If ngModel was undefined
1141 for (var k = inputValue.length - 1; k >= 0; k--) {
1142 //Check model array of currently selected items
1143 if (!checkFnMultiple($select.selected, inputValue[k])){
1144 //Check model array of all items available
1145 if (!checkFnMultiple(data, inputValue[k])){
1146 //If not found on previous lists, just add it directly to resultMultiple
1147 resultMultiple.unshift(inputValue[k]);
1151 return resultMultiple;
1154 //Watch for external model changes
1155 scope.$watchCollection(function(){ return ngModel.$modelValue; }, function(newValue, oldValue) {
1156 if (oldValue != newValue){
1157 ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters
1158 $selectMultiple.refreshComponent();
1162 ngModel.$render = function() {
1163 // Make sure that model value is array
1164 if(!angular.isArray(ngModel.$viewValue)){
1165 // Have tolerance for null or undefined values
1166 if(angular.isUndefined(ngModel.$viewValue) || ngModel.$viewValue === null){
1167 $select.selected = [];
1169 throw uiSelectMinErr('multiarr', "Expected model value to be array but got '{0}'", ngModel.$viewValue);
1172 $select.selected = ngModel.$viewValue;
1173 scope.$evalAsync(); //To force $digest
1176 scope.$on('uis:select', function (event, item) {
1177 $select.selected.push(item);
1178 $selectMultiple.updateModel();
1181 scope.$on('uis:activate', function () {
1182 $selectMultiple.activeMatchIndex = -1;
1185 scope.$watch('$select.disabled', function(newValue, oldValue) {
1186 // As the search input field may now become visible, it may be necessary to ronapute its size
1187 if (oldValue && !newValue) $select.sizeSearchInput();
1190 $select.searchInput.on('keydown', function(e) {
1192 scope.$apply(function() {
1193 var processed = false;
1194 // var tagged = false; //Checkme
1195 if(KEY.isHorizontalMovement(key)){
1196 processed = _handleMatchSelection(key);
1198 if (processed && key != KEY.TAB) {
1199 //TODO Check si el tab selecciona aun correctamente
1202 e.stopPropagation();
1206 function _getCaretPosition(el) {
1207 if(angular.isNumber(el.selectionStart)) return el.selectionStart;
1208 // selectionStart is not supported in IE8 and we don't want hacky workarounds so we compromise
1209 else return el.value.length;
1211 // Handles selected options in "multiple" mode
1212 function _handleMatchSelection(key){
1213 var caretPosition = _getCaretPosition($select.searchInput[0]),
1214 length = $select.selected.length,
1218 curr = $selectMultiple.activeMatchIndex,
1219 next = $selectMultiple.activeMatchIndex+1,
1220 prev = $selectMultiple.activeMatchIndex-1,
1223 if(caretPosition > 0 || ($select.search.length && key == KEY.RIGHT)) return false;
1227 function getNewActiveMatchIndex(){
1230 // Select previous/first item
1231 if(~$selectMultiple.activeMatchIndex) return prev;
1237 if(!~$selectMultiple.activeMatchIndex || curr === last){
1241 // Select next/last item
1245 // Remove selected item and select previous/first
1246 if(~$selectMultiple.activeMatchIndex){
1247 $selectMultiple.removeChoice(curr);
1254 // Remove selected item and select next item
1255 if(~$selectMultiple.activeMatchIndex){
1256 $selectMultiple.removeChoice($selectMultiple.activeMatchIndex);
1263 newIndex = getNewActiveMatchIndex();
1265 if(!$select.selected.length || newIndex === false) $selectMultiple.activeMatchIndex = -1;
1266 else $selectMultiple.activeMatchIndex = Math.min(last,Math.max(first,newIndex));
1271 $select.searchInput.on('keyup', function(e) {
1273 if ( ! KEY.isVerticalMovement(e.which) ) {
1274 scope.$evalAsync( function () {
1275 $select.activeIndex = $select.taggingLabel === false ? -1 : 0;
1278 // Push a "create new" item into array if there is a search string
1279 if ( $select.tagging.isActivated && $select.search.length > 0 ) {
1281 // return early with these keys
1282 if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || KEY.isVerticalMovement(e.which) ) {
1285 // always reset the activeIndex to the first item when tagging
1286 $select.activeIndex = $select.taggingLabel === false ? -1 : 0;
1287 // taggingLabel === false bypasses all of this
1288 if ($select.taggingLabel === false) return;
1290 var items = angular.copy( $select.items );
1291 var stashArr = angular.copy( $select.items );
1299 // case for object tagging via transform `$select.tagging.fct` function
1300 if ( $select.tagging.fct !== undefined) {
1301 tagItems = $select.$filter('filter')(items,{'isTag': true});
1302 if ( tagItems.length > 0 ) {
1303 tagItem = tagItems[0];
1305 // remove the first element, if it has the `isTag` prop we generate a new one with each keyup, shaving the previous
1306 if ( items.length > 0 && tagItem ) {
1308 items = items.slice(1,items.length);
1309 stashArr = stashArr.slice(1,stashArr.length);
1311 newItem = $select.tagging.fct($select.search);
1312 newItem.isTag = true;
1313 // verify the the tag doesn't match the value of an existing item
1314 if ( stashArr.filter( function (origItem) { return angular.equals( origItem, $select.tagging.fct($select.search) ); } ).length > 0 ) {
1317 newItem.isTag = true;
1318 // handle newItem string and stripping dupes in tagging string context
1320 // find any tagging items already in the $select.items array and store them
1321 tagItems = $select.$filter('filter')(items,function (item) {
1322 return item.match($select.taggingLabel);
1324 if ( tagItems.length > 0 ) {
1325 tagItem = tagItems[0];
1328 // remove existing tag item if found (should only ever be one tag item)
1329 if ( item !== undefined && items.length > 0 && tagItem ) {
1331 items = items.slice(1,items.length);
1332 stashArr = stashArr.slice(1,stashArr.length);
1334 newItem = $select.search+' '+$select.taggingLabel;
1335 if ( _findApproxDupe($select.selected, $select.search) > -1 ) {
1338 // verify the the tag doesn't match the value of an existing item from
1339 // the searched data set or the items already selected
1340 if ( _findCaseInsensitiveDupe(stashArr.concat($select.selected)) ) {
1341 // if there is a tag from prev iteration, strip it / queue the change
1345 scope.$evalAsync( function () {
1346 $select.activeIndex = 0;
1347 $select.items = items;
1352 if ( _findCaseInsensitiveDupe(stashArr) ) {
1353 // if there is a tag from prev iteration, strip it
1355 $select.items = stashArr.slice(1,stashArr.length);
1360 if ( hasTag ) dupeIndex = _findApproxDupe($select.selected, newItem);
1361 // dupe found, shave the first item
1362 if ( dupeIndex > -1 ) {
1363 items = items.slice(dupeIndex+1,items.length-1);
1366 items.push(newItem);
1367 items = items.concat(stashArr);
1369 scope.$evalAsync( function () {
1370 $select.activeIndex = 0;
1371 $select.items = items;
1375 function _findCaseInsensitiveDupe(arr) {
1376 if ( arr === undefined || $select.search === undefined ) {
1379 var hasDupe = arr.filter( function (origItem) {
1380 if ( $select.search.toUpperCase() === undefined || origItem === undefined ) {
1383 return origItem.toUpperCase() === $select.search.toUpperCase();
1388 function _findApproxDupe(haystack, needle) {
1390 if(angular.isArray(haystack)) {
1391 var tempArr = angular.copy(haystack);
1392 for (var i = 0; i <tempArr.length; i++) {
1393 // handle the simple string version of tagging
1394 if ( $select.tagging.fct === undefined ) {
1395 // search the array for the match
1396 if ( tempArr[i]+' '+$select.taggingLabel === needle ) {
1399 // handle the object tagging implementation
1401 var mockObj = tempArr[i];
1402 mockObj.isTag = true;
1403 if ( angular.equals(mockObj, needle) ) {
1412 $select.searchInput.on('blur', function() {
1413 $timeout(function() {
1414 $selectMultiple.activeMatchIndex = -1;
1421 uis.directive('uiSelectSingle', ['$timeout','$compile', function($timeout, $compile) {
1424 require: ['^uiSelect', '^ngModel'],
1425 link: function(scope, element, attrs, ctrls) {
1427 var $select = ctrls[0];
1428 var ngModel = ctrls[1];
1430 //From view --> model
1431 ngModel.$parsers.unshift(function (inputValue) {
1434 locals[$select.parserResult.itemName] = inputValue;
1435 result = $select.parserResult.modelMapper(scope, locals);
1439 //From model --> view
1440 ngModel.$formatters.unshift(function (inputValue) {
1441 var data = $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search
1445 var checkFnSingle = function(d){
1446 locals[$select.parserResult.itemName] = d;
1447 result = $select.parserResult.modelMapper(scope, locals);
1448 return result == inputValue;
1450 //If possible pass same object stored in $select.selected
1451 if ($select.selected && checkFnSingle($select.selected)) {
1452 return $select.selected;
1454 for (var i = data.length - 1; i >= 0; i--) {
1455 if (checkFnSingle(data[i])) return data[i];
1461 //Update viewValue if model change
1462 scope.$watch('$select.selected', function(newValue) {
1463 if (ngModel.$viewValue !== newValue) {
1464 ngModel.$setViewValue(newValue);
1468 ngModel.$render = function() {
1469 $select.selected = ngModel.$viewValue;
1472 scope.$on('uis:select', function (event, item) {
1473 $select.selected = item;
1476 scope.$on('uis:close', function (event, skipFocusser) {
1477 $timeout(function(){
1478 $select.focusser.prop('disabled', false);
1479 if (!skipFocusser) $select.focusser[0].focus();
1483 scope.$on('uis:activate', function () {
1484 focusser.prop('disabled', true); //Will reactivate it on .close()
1487 //Idea from: https://github.com/ivaynberg/select2/blob/79b5bf6db918d7560bdd959109b7bcfb47edaf43/select2.js#L1954
1488 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' />");
1489 $compile(focusser)(scope);
1490 $select.focusser = focusser;
1492 //Input that will handle focus
1493 $select.focusInput = focusser;
1495 element.parent().append(focusser);
1496 focusser.bind("focus", function(){
1497 scope.$evalAsync(function(){
1498 $select.focus = true;
1501 focusser.bind("blur", function(){
1502 scope.$evalAsync(function(){
1503 $select.focus = false;
1506 focusser.bind("keydown", function(e){
1508 if (e.which === KEY.BACKSPACE) {
1510 e.stopPropagation();
1511 $select.select(undefined);
1516 if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
1520 if (e.which == KEY.DOWN || e.which == KEY.UP || e.which == KEY.ENTER || e.which == KEY.SPACE){
1522 e.stopPropagation();
1529 focusser.bind("keyup input", function(e){
1531 if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || e.which == KEY.ENTER || e.which === KEY.BACKSPACE) {
1535 $select.activate(focusser.val()); //User pressed some regular key, so we pass it to the search input
1545 // Make multiple matches sortable
1546 uis.directive('uiSelectSort', ['$timeout', 'uiSelectConfig', 'uiSelectMinErr', function($timeout, uiSelectConfig, uiSelectMinErr) {
1548 require: '^uiSelect',
1549 link: function(scope, element, attrs, $select) {
1550 if (scope[attrs.uiSelectSort] === null) {
1551 throw uiSelectMinErr('sort', "Expected a list to sort");
1554 var options = angular.extend({
1557 scope.$eval(attrs.uiSelectSortOptions));
1559 var axis = options.axis,
1560 draggingClassName = 'dragging',
1561 droppingClassName = 'dropping',
1562 droppingBeforeClassName = 'dropping-before',
1563 droppingAfterClassName = 'dropping-after';
1565 scope.$watch(function(){
1566 return $select.sortable;
1569 element.attr('draggable', true);
1571 element.removeAttr('draggable');
1575 element.on('dragstart', function(e) {
1576 element.addClass(draggingClassName);
1578 (e.dataTransfer || e.originalEvent.dataTransfer).setData('text/plain', scope.$index);
1581 element.on('dragend', function() {
1582 element.removeClass(draggingClassName);
1585 var move = function(from, to) {
1586 /*jshint validthis: true */
1587 this.splice(to, 0, this.splice(from, 1)[0]);
1590 var dragOverHandler = function(e) {
1593 var offset = axis === 'vertical' ? e.offsetY || e.layerY || (e.originalEvent ? e.originalEvent.offsetY : 0) : e.offsetX || e.layerX || (e.originalEvent ? e.originalEvent.offsetX : 0);
1595 if (offset < (this[axis === 'vertical' ? 'offsetHeight' : 'offsetWidth'] / 2)) {
1596 element.removeClass(droppingAfterClassName);
1597 element.addClass(droppingBeforeClassName);
1600 element.removeClass(droppingBeforeClassName);
1601 element.addClass(droppingAfterClassName);
1607 var dropHandler = function(e) {
1610 var droppedItemIndex = parseInt((e.dataTransfer || e.originalEvent.dataTransfer).getData('text/plain'), 10);
1612 // prevent event firing multiple times in firefox
1613 $timeout.cancel(dropTimeout);
1614 dropTimeout = $timeout(function() {
1615 _dropHandler(droppedItemIndex);
1619 var _dropHandler = function(droppedItemIndex) {
1620 var theList = scope.$eval(attrs.uiSelectSort),
1621 itemToMove = theList[droppedItemIndex],
1624 if (element.hasClass(droppingBeforeClassName)) {
1625 if (droppedItemIndex < scope.$index) {
1626 newIndex = scope.$index - 1;
1628 newIndex = scope.$index;
1631 if (droppedItemIndex < scope.$index) {
1632 newIndex = scope.$index;
1634 newIndex = scope.$index + 1;
1638 move.apply(theList, [droppedItemIndex, newIndex]);
1640 scope.$apply(function() {
1641 scope.$emit('uiSelectSort:change', {
1644 from: droppedItemIndex,
1649 element.removeClass(droppingClassName);
1650 element.removeClass(droppingBeforeClassName);
1651 element.removeClass(droppingAfterClassName);
1653 element.off('drop', dropHandler);
1656 element.on('dragenter', function() {
1657 if (element.hasClass(draggingClassName)) {
1661 element.addClass(droppingClassName);
1663 element.on('dragover', dragOverHandler);
1664 element.on('drop', dropHandler);
1667 element.on('dragleave', function(e) {
1668 if (e.target != element) {
1671 element.removeClass(droppingClassName);
1672 element.removeClass(droppingBeforeClassName);
1673 element.removeClass(droppingAfterClassName);
1675 element.off('dragover', dragOverHandler);
1676 element.off('drop', dropHandler);
1683 * Parses "repeat" attribute.
1685 * Taken from AngularJS ngRepeat source code
1686 * See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L211
1688 * Original discussion about parsing "repeat" attribute instead of fully relying on ng-repeat:
1689 * https://github.com/angular-ui/ui-select/commit/5dd63ad#commitcomment-5504697
1692 uis.service('uisRepeatParser', ['uiSelectMinErr','$parse', function(uiSelectMinErr, $parse) {
1697 * expression = "address in addresses | filter: {street: $select.search} track by $index"
1698 * itemName = "address",
1699 * source = "addresses | filter: {street: $select.search}",
1700 * trackByExp = "$index",
1702 self.parse = function(expression) {
1704 var match = expression.match(/^\s*(?:([\s\S]+?)\s+as\s+)?([\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
1707 throw uiSelectMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
1712 itemName: match[2], // (lhs) Left-hand side,
1713 source: $parse(match[3]),
1714 trackByExp: match[4],
1715 modelMapper: $parse(match[1] || match[2])
1720 self.getGroupNgRepeatExpression = function() {
1721 return '$group in $select.groups';
1724 self.getNgRepeatExpression = function(itemName, source, trackByExp, grouped) {
1725 var expression = itemName + ' in ' + (grouped ? '$group.items' : source);
1727 expression += ' track by ' + trackByExp;
1734 angular.module("ui.select").run(["$templateCache", function($templateCache) {$templateCache.put("bootstrap/choices.tpl.html","<ul class=\"ui-select-choices ui-select-choices-content dropdown-menu\" role=\"listbox\" ng-show=\"$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 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\"><a href=\"javascript:void(0)\" class=\"ui-select-choices-row-inner\"></a></div></li></ul>");
1735 $templateCache.put("bootstrap/match-multiple.tpl.html","<span class=\"ui-select-match\"><span ng-repeat=\"$item in $select.selected\"><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)\"> ×</span> <span uis-transclude-append=\"\"></span></span></span></span>");
1736 $templateCache.put("bootstrap/match.tpl.html","<div class=\"ui-select-match\" ng-hide=\"$select.open\" ng-disabled=\"$select.disabled\" ng-class=\"{\'btn-default-focus\':$select.focus}\"><span tabindex=\"-1\" class=\"btn btn-default form-control ui-select-toggle\" aria-label=\"{{ $select.baseTitle }} activate\" ng-disabled=\"$select.disabled\" ng-click=\"$select.activate()\" style=\"outline: 0;\"><span ng-show=\"$select.isEmpty()\" class=\"ui-select-placeholder text-muted\">{{$select.placeholder}}</span> <span ng-hide=\"$select.isEmpty()\" class=\"ui-select-match-text pull-left\" ng-class=\"{\'ui-select-allow-clear\': $select.allowClear && !$select.isEmpty()}\" ng-transclude=\"\"></span> <i class=\"caret pull-right\" ng-click=\"$select.toggle($event)\"></i> <a ng-show=\"$select.allowClear && !$select.isEmpty()\" 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>");
1737 $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=\"text\" autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" class=\"ui-select-search input-xs\" placeholder=\"{{$selectMultiple.getPlaceholder()}}\" ng-disabled=\"$select.disabled\" ng-hide=\"$select.disabled\" ng-click=\"$select.activate()\" ng-model=\"$select.search\" role=\"combobox\" aria-label=\"{{ $select.baseTitle }}\" ondrop=\"return false;\"></div><div class=\"ui-select-choices\"></div></div>");
1738 $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><input type=\"text\" autocomplete=\"off\" tabindex=\"-1\" aria-expanded=\"true\" aria-label=\"{{ $select.baseTitle }}\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" aria-activedescendant=\"ui-select-choices-row-{{ $select.generatedId }}-{{ $select.activeIndex }}\" class=\"form-control ui-select-search\" placeholder=\"{{$select.placeholder}}\" ng-model=\"$select.search\" ng-show=\"$select.searchEnabled && $select.open\"><div class=\"ui-select-choices\"></div></div>");
1739 $templateCache.put("select2/choices.tpl.html","<ul 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 role=\"listbox\" id=\"ui-select-choices-{{ $select.generatedId }}\" ng-class=\"{\'select2-result-sub\': $select.choiceGrouped($group), \'select2-result-single\': !$select.choiceGrouped($group) }\"><li role=\"option\" 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>");
1740 $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\" ng-class=\"{\'select2-search-choice-focus\':$selectMultiple.activeMatchIndex === $index, \'select2-locked\':$select.isLocked(this, $index)}\" ui-select-sort=\"$select.selected\"><span uis-transclude-append=\"\"></span> <a href=\"javascript:;\" class=\"ui-select-match-close select2-search-choice-close\" ng-click=\"$selectMultiple.removeChoice($index)\" tabindex=\"-1\"></a></li></span>");
1741 $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>");
1742 $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=\"text\" 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=\"select2-drop select2-with-searchbox select2-drop-active\" ng-class=\"{\'select2-display-none\': !$select.open}\"><div class=\"ui-select-choices\"></div></div></div>");
1743 $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=\"select2-drop select2-with-searchbox select2-drop-active\" ng-class=\"{\'select2-display-none\': !$select.open}\"><div class=\"select2-search\" ng-show=\"$select.searchEnabled\"><input type=\"text\" 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=\"ui-select-search select2-input\" ng-model=\"$select.search\"></div><div class=\"ui-select-choices\"></div></div></div>");
1744 $templateCache.put("selectize/choices.tpl.html","<div ng-show=\"$select.open\" class=\"ui-select-choices selectize-dropdown single\"><div class=\"ui-select-choices-content selectize-dropdown-content\"><div class=\"ui-select-choices-group optgroup\" role=\"listbox\"><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>");
1745 $templateCache.put("selectize/match.tpl.html","<div ng-hide=\"($select.open || $select.isEmpty())\" class=\"ui-select-match\" ng-transclude=\"\"></div>");
1746 $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.activate()\"><div class=\"ui-select-match\"></div><input type=\"text\" autocomplete=\"off\" tabindex=\"-1\" class=\"ui-select-search ui-select-toggle\" ng-click=\"$select.toggle($event)\" placeholder=\"{{$select.placeholder}}\" ng-model=\"$select.search\" ng-hide=\"!$select.searchEnabled || ($select.selected && !$select.open)\" ng-disabled=\"$select.disabled\" aria-label=\"{{ $select.baseTitle }}\"></div><div class=\"ui-select-choices\"></div></div>");}]);