This repository was archived by the owner on Oct 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathuiSelectController.js
747 lines (657 loc) · 24.7 KB
/
uiSelectController.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
/**
* Contains ui-select "intelligence".
*
* The goal is to limit dependency on the DOM whenever possible and
* put as much logic in the controller (instead of the link functions) as possible so it can be easily tested.
*/
uis.controller('uiSelectCtrl',
['$scope', '$element', '$timeout', '$filter', 'RepeatParser', 'uiSelectMinErr', 'uiSelectConfig',
function($scope, $element, $timeout, $filter, RepeatParser, uiSelectMinErr, uiSelectConfig) {
var ctrl = this;
var EMPTY_SEARCH = '';
ctrl.placeholder = uiSelectConfig.placeholder;
ctrl.search = EMPTY_SEARCH;
ctrl.activeIndex = 0;
ctrl.activeMatchIndex = -1;
ctrl.items = [];
ctrl.selected = undefined;
ctrl.open = false;
ctrl.focus = false;
ctrl.focusser = undefined; //Reference to input element used to handle focus events
ctrl.disabled = false;
ctrl.searchEnabled = uiSelectConfig.searchEnabled;
ctrl.sortable = uiSelectConfig.sortable;
ctrl.resetSearchInput = true;
ctrl.multiple = undefined; // Initialized inside uiSelect directive link function
ctrl.refreshDelay = uiSelectConfig.refreshDelay;
ctrl.disableChoiceExpression = undefined; // Initialized inside uiSelectChoices directive link function
ctrl.tagging = {isActivated: false, fct: undefined};
ctrl.taggingTokens = {isActivated: false, tokens: undefined};
ctrl.lockChoiceExpression = undefined; // Initialized inside uiSelectMatch directive link function
ctrl.closeOnSelect = true; // Initialized inside uiSelect directive link function
ctrl.clickTriggeredSelect = false;
ctrl.$filter = $filter;
ctrl.isEmpty = function() {
return angular.isUndefined(ctrl.selected) || ctrl.selected === null || ctrl.selected === '';
};
var _searchInput = $element.querySelectorAll('input.ui-select-search');
if (_searchInput.length !== 1) {
throw uiSelectMinErr('searchInput', "Expected 1 input.ui-select-search but got '{0}'.", _searchInput.length);
}
// Most of the time the user does not want to empty the search input when in typeahead mode
function _resetSearchInput() {
if (ctrl.resetSearchInput || (ctrl.resetSearchInput === undefined && uiSelectConfig.resetSearchInput)) {
ctrl.search = EMPTY_SEARCH;
//reset activeIndex
if (ctrl.selected && ctrl.items.length && !ctrl.multiple) {
ctrl.activeIndex = ctrl.items.indexOf(ctrl.selected);
}
}
}
// When the user clicks on ui-select, displays the dropdown list
ctrl.activate = function(initSearchValue, avoidReset) {
if (!ctrl.disabled && !ctrl.open) {
if(!avoidReset) _resetSearchInput();
ctrl.focusser.prop('disabled', true); //Will reactivate it on .close()
ctrl.open = true;
ctrl.activeMatchIndex = -1;
ctrl.activeIndex = ctrl.activeIndex >= ctrl.items.length ? 0 : ctrl.activeIndex;
// ensure that the index is set to zero for tagging variants
// that where first option is auto-selected
if ( ctrl.activeIndex === -1 && ctrl.taggingLabel !== false ) {
ctrl.activeIndex = 0;
}
// Give it time to appear before focus
$timeout(function() {
ctrl.search = initSearchValue || ctrl.search;
_searchInput[0].focus();
});
}
};
ctrl.findGroupByName = function(name) {
return ctrl.groups && ctrl.groups.filter(function(group) {
return group.name === name;
})[0];
};
ctrl.parseRepeatAttr = function(repeatAttr, groupByExp) {
function updateGroups(items) {
ctrl.groups = [];
angular.forEach(items, function(item) {
var groupFn = $scope.$eval(groupByExp);
var groupName = angular.isFunction(groupFn) ? groupFn(item) : item[groupFn];
var group = ctrl.findGroupByName(groupName);
if(group) {
group.items.push(item);
}
else {
ctrl.groups.push({name: groupName, items: [item]});
}
});
ctrl.items = [];
ctrl.groups.forEach(function(group) {
ctrl.items = ctrl.items.concat(group.items);
});
}
function setPlainItems(items) {
ctrl.items = items;
}
var setItemsFn = groupByExp ? updateGroups : setPlainItems;
ctrl.parserResult = RepeatParser.parse(repeatAttr);
ctrl.isGrouped = !!groupByExp;
ctrl.itemProperty = ctrl.parserResult.itemName;
// See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L259
$scope.$watchCollection(ctrl.parserResult.source, function(items) {
if (items === undefined || items === null) {
// If the user specifies undefined or null => reset the collection
// Special case: items can be undefined if the user did not initialized the collection on the scope
// i.e $scope.addresses = [] is missing
ctrl.items = [];
} else {
if (!angular.isArray(items)) {
throw uiSelectMinErr('items', "Expected an array but got '{0}'.", items);
} else {
if (ctrl.multiple){
//Remove already selected items (ex: while searching)
var filteredItems = items.filter(function(i) {return ctrl.selected.indexOf(i) < 0;});
setItemsFn(filteredItems);
}else{
setItemsFn(items);
}
ctrl.ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters
}
}
});
if (ctrl.multiple){
//Remove already selected items
$scope.$watchCollection('$select.selected', function(selectedItems){
var data = ctrl.parserResult.source($scope);
if (!selectedItems.length) {
setItemsFn(data);
}else{
if ( data !== undefined ) {
var filteredItems = data.filter(function(i) {return selectedItems.indexOf(i) < 0;});
setItemsFn(filteredItems);
}
}
ctrl.sizeSearchInput();
});
}
};
var _refreshDelayPromise;
/**
* Typeahead mode: lets the user refresh the collection using his own function.
*
* See Expose $select.search for external / remote filtering https://github.com/angular-ui/ui-select/pull/31
*/
ctrl.refresh = function(refreshAttr) {
if (refreshAttr !== undefined) {
// Debounce
// See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L155
// FYI AngularStrap typeahead does not have debouncing: https://github.com/mgcrea/angular-strap/blob/v2.0.0-rc.4/src/typeahead/typeahead.js#L177
if (_refreshDelayPromise) {
$timeout.cancel(_refreshDelayPromise);
}
_refreshDelayPromise = $timeout(function() {
$scope.$eval(refreshAttr);
}, ctrl.refreshDelay);
}
};
ctrl.setActiveItem = function(item) {
ctrl.activeIndex = ctrl.items.indexOf(item);
};
ctrl.isActive = function(itemScope) {
if ( !ctrl.open ) {
return false;
}
var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]);
var isActive = itemIndex === ctrl.activeIndex;
if ( !isActive || ( itemIndex < 0 && ctrl.taggingLabel !== false ) ||( itemIndex < 0 && ctrl.taggingLabel === false) ) {
return false;
}
if (isActive && !angular.isUndefined(ctrl.onHighlightCallback)) {
itemScope.$eval(ctrl.onHighlightCallback);
}
return isActive;
};
ctrl.isDisabled = function(itemScope) {
if (!ctrl.open) return;
var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]);
var isDisabled = false;
var item;
if (itemIndex >= 0 && !angular.isUndefined(ctrl.disableChoiceExpression)) {
item = ctrl.items[itemIndex];
isDisabled = !!(itemScope.$eval(ctrl.disableChoiceExpression)); // force the boolean value
item._uiSelectChoiceDisabled = isDisabled; // store this for later reference
}
return isDisabled;
};
// When the user selects an item with ENTER or clicks the dropdown
ctrl.select = function(item, skipFocusser, $event) {
if (item === undefined || !item._uiSelectChoiceDisabled) {
if ( ! ctrl.items && ! ctrl.search ) return;
if (!item || !item._uiSelectChoiceDisabled) {
if(ctrl.tagging.isActivated) {
// if taggingLabel is disabled, we pull from ctrl.search val
if ( ctrl.taggingLabel === false ) {
if ( ctrl.activeIndex < 0 ) {
item = ctrl.tagging.fct !== undefined ? ctrl.tagging.fct(ctrl.search) : ctrl.search;
if (!item || angular.equals( ctrl.items[0], item ) ) {
return;
}
} else {
// keyboard nav happened first, user selected from dropdown
item = ctrl.items[ctrl.activeIndex];
}
} else {
// tagging always operates at index zero, taggingLabel === false pushes
// the ctrl.search value without having it injected
if ( ctrl.activeIndex === 0 ) {
// ctrl.tagging pushes items to ctrl.items, so we only have empty val
// for `item` if it is a detected duplicate
if ( item === undefined ) return;
// create new item on the fly if we don't already have one;
// use tagging function if we have one
if ( ctrl.tagging.fct !== undefined && typeof item === 'string' ) {
item = ctrl.tagging.fct(ctrl.search);
if (!item) return;
// if item type is 'string', apply the tagging label
} else if ( typeof item === 'string' ) {
// trim the trailing space
item = item.replace(ctrl.taggingLabel,'').trim();
}
}
}
// search ctrl.selected for dupes potentially caused by tagging and return early if found
if ( ctrl.selected && angular.isArray(ctrl.selected) && ctrl.selected.filter( function (selection) { return angular.equals(selection, item); }).length > 0 ) {
ctrl.close(skipFocusser);
return;
}
}
var locals = {};
locals[ctrl.parserResult.itemName] = item;
if(ctrl.multiple) {
ctrl.selected.push(item);
ctrl.sizeSearchInput();
} else {
ctrl.selected = item;
}
$timeout(function(){
ctrl.onSelectCallback($scope, {
$item: item,
$model: ctrl.parserResult.modelMapper($scope, locals)
});
});
if (!ctrl.multiple || ctrl.closeOnSelect) {
ctrl.close(skipFocusser);
}
if ($event && $event.type === 'click') {
ctrl.clickTriggeredSelect = true;
}
}
}
};
// Closes the dropdown
ctrl.close = function(skipFocusser) {
if (!ctrl.open) return;
if (ctrl.ngModel && ctrl.ngModel.$setTouched) ctrl.ngModel.$setTouched();
_resetSearchInput();
ctrl.open = false;
if (!ctrl.multiple){
$timeout(function(){
ctrl.focusser.prop('disabled', false);
if (!skipFocusser) ctrl.focusser[0].focus();
},0,false);
}
};
ctrl.clear = function($event) {
ctrl.select(undefined);
$event.stopPropagation();
ctrl.focusser[0].focus();
};
// Toggle dropdown
ctrl.toggle = function(e) {
if (ctrl.open) {
ctrl.close();
e.preventDefault();
e.stopPropagation();
} else {
ctrl.activate();
}
};
ctrl.isLocked = function(itemScope, itemIndex) {
var isLocked, item = ctrl.selected[itemIndex];
if (item && !angular.isUndefined(ctrl.lockChoiceExpression)) {
isLocked = !!(itemScope.$eval(ctrl.lockChoiceExpression)); // force the boolean value
item._uiSelectChoiceLocked = isLocked; // store this for later reference
}
return isLocked;
};
// Remove item from multiple select
ctrl.removeChoice = function(index){
var removedChoice = ctrl.selected[index];
// if the choice is locked, can't remove it
if(removedChoice._uiSelectChoiceLocked) return;
var locals = {};
locals[ctrl.parserResult.itemName] = removedChoice;
ctrl.selected.splice(index, 1);
ctrl.activeMatchIndex = -1;
ctrl.sizeSearchInput();
// Give some time for scope propagation.
$timeout(function(){
ctrl.onRemoveCallback($scope, {
$item: removedChoice,
$model: ctrl.parserResult.modelMapper($scope, locals)
});
});
};
ctrl.getPlaceholder = function(){
//Refactor single?
if(ctrl.multiple && ctrl.selected.length) return;
return ctrl.placeholder;
};
var containerSizeWatch;
ctrl.sizeSearchInput = function(){
var input = _searchInput[0],
container = _searchInput.parent().parent()[0];
_searchInput.css('width','10px');
var calculate = function(){
var newWidth = container.clientWidth - input.offsetLeft - 10;
if(newWidth < 50) newWidth = container.clientWidth;
_searchInput.css('width',newWidth+'px');
};
$timeout(function(){ //Give tags time to render correctly
if (container.clientWidth === 0 && !containerSizeWatch){
containerSizeWatch = $scope.$watch(function(){ return container.clientWidth;}, function(newValue){
if (newValue !== 0){
calculate();
containerSizeWatch();
containerSizeWatch = null;
}
});
}else if (!containerSizeWatch) {
calculate();
}
}, 0, false);
};
function _handleDropDownSelection(key) {
var processed = true;
switch (key) {
case KEY.DOWN:
if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode
else if (ctrl.activeIndex < ctrl.items.length - 1) { ctrl.activeIndex++; }
break;
case KEY.UP:
if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode
else if (ctrl.activeIndex > 0 || (ctrl.search.length === 0 && ctrl.tagging.isActivated && ctrl.activeIndex > -1)) { ctrl.activeIndex--; }
break;
case KEY.TAB:
if (!ctrl.multiple || ctrl.open) ctrl.select(ctrl.items[ctrl.activeIndex], true);
break;
case KEY.ENTER:
if(ctrl.open && ctrl.activeIndex >= 0){
ctrl.select(ctrl.items[ctrl.activeIndex]); // Make sure at least one dropdown item is highlighted before adding.
} else {
ctrl.activate(false, true); //In case its the search input in 'multiple' mode
}
break;
case KEY.ESC:
ctrl.close();
break;
default:
processed = false;
}
return processed;
}
// Handles selected options in "multiple" mode
function _handleMatchSelection(key){
var caretPosition = _getCaretPosition(_searchInput[0]),
length = ctrl.selected.length,
// none = -1,
first = 0,
last = length-1,
curr = ctrl.activeMatchIndex,
next = ctrl.activeMatchIndex+1,
prev = ctrl.activeMatchIndex-1,
newIndex = curr;
if(caretPosition > 0 || (ctrl.search.length && key == KEY.RIGHT)) return false;
ctrl.close();
function getNewActiveMatchIndex(){
switch(key){
case KEY.LEFT:
// Select previous/first item
if(~ctrl.activeMatchIndex) return prev;
// Select last item
else return last;
break;
case KEY.RIGHT:
// Open drop-down
if(!~ctrl.activeMatchIndex || curr === last){
ctrl.activate();
return false;
}
// Select next/last item
else return next;
break;
case KEY.BACKSPACE:
// Remove selected item and select previous/first
if(~ctrl.activeMatchIndex){
ctrl.removeChoice(curr);
return prev;
}
// Select last item
else return last;
break;
case KEY.DELETE:
// Remove selected item and select next item
if(~ctrl.activeMatchIndex){
ctrl.removeChoice(ctrl.activeMatchIndex);
return curr;
}
else return false;
}
}
newIndex = getNewActiveMatchIndex();
if(!ctrl.selected.length || newIndex === false) ctrl.activeMatchIndex = -1;
else ctrl.activeMatchIndex = Math.min(last,Math.max(first,newIndex));
return true;
}
// Bind to keyboard shortcuts
_searchInput.on('keydown', function(e) {
var key = e.which;
// if(~[KEY.ESC,KEY.TAB].indexOf(key)){
// //TODO: SEGURO?
// ctrl.close();
// }
$scope.$apply(function() {
var processed = false;
var tagged = false;
if(ctrl.multiple && KEY.isHorizontalMovement(key)){
processed = _handleMatchSelection(key);
}
if (!processed && (ctrl.items.length > 0 || ctrl.tagging.isActivated)) {
processed = _handleDropDownSelection(key);
if ( ctrl.taggingTokens.isActivated ) {
for (var i = 0; i < ctrl.taggingTokens.tokens.length; i++) {
if ( ctrl.taggingTokens.tokens[i] === KEY.MAP[e.keyCode] ) {
// make sure there is a new value to push via tagging
if ( ctrl.search.length > 0 ) {
tagged = true;
}
}
}
if ( tagged ) {
$timeout(function() {
_searchInput.triggerHandler('tagged');
var newItem = ctrl.search.replace(KEY.MAP[e.keyCode],'').trim();
if ( ctrl.tagging.fct ) {
newItem = ctrl.tagging.fct( newItem );
}
if (newItem) ctrl.select(newItem, true);
});
}
}
}
if (processed && key != KEY.TAB) {
//TODO Check si el tab selecciona aun correctamente
//Crear test
e.preventDefault();
e.stopPropagation();
}
});
if(KEY.isVerticalMovement(key) && ctrl.items.length > 0){
_ensureHighlightVisible();
}
});
// If tagging try to split by tokens and add items
_searchInput.on('paste', function (e) {
var data = e.originalEvent.clipboardData.getData('text/plain');
if (data && data.length > 0 && ctrl.taggingTokens.isActivated && ctrl.tagging.fct) {
var items = data.split(ctrl.taggingTokens.tokens[0]); // split by first token only
if (items && items.length > 0) {
angular.forEach(items, function (item) {
var newItem = ctrl.tagging.fct(item);
if (newItem) {
ctrl.select(newItem, true);
}
});
e.preventDefault();
e.stopPropagation();
}
}
});
_searchInput.on('keyup', function(e) {
if ( ! KEY.isVerticalMovement(e.which) ) {
$scope.$evalAsync( function () {
ctrl.activeIndex = ctrl.taggingLabel === false ? -1 : 0;
});
}
// Push a "create new" item into array if there is a search string
if ( ctrl.tagging.isActivated && ctrl.search.length > 0 ) {
// return early with these keys
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || KEY.isVerticalMovement(e.which) ) {
return;
}
// always reset the activeIndex to the first item when tagging
ctrl.activeIndex = ctrl.taggingLabel === false ? -1 : 0;
// taggingLabel === false bypasses all of this
if (ctrl.taggingLabel === false) return;
var items = angular.copy( ctrl.items );
var stashArr = angular.copy( ctrl.items );
var newItem;
var item;
var hasTag = false;
var dupeIndex = -1;
var tagItems;
var tagItem;
// case for object tagging via transform `ctrl.tagging.fct` function
if ( ctrl.tagging.fct !== undefined) {
tagItems = ctrl.$filter('filter')(items,{'isTag': true});
if ( tagItems.length > 0 ) {
tagItem = tagItems[0];
}
// remove the first element, if it has the `isTag` prop we generate a new one with each keyup, shaving the previous
if ( items.length > 0 && tagItem ) {
hasTag = true;
items = items.slice(1,items.length);
stashArr = stashArr.slice(1,stashArr.length);
}
newItem = ctrl.tagging.fct(ctrl.search);
newItem.isTag = true;
// verify the the tag doesn't match the value of an existing item
if ( stashArr.filter( function (origItem) { return angular.equals( origItem, ctrl.tagging.fct(ctrl.search) ); } ).length > 0 ) {
return;
}
newItem.isTag = true;
// handle newItem string and stripping dupes in tagging string context
} else {
// find any tagging items already in the ctrl.items array and store them
tagItems = ctrl.$filter('filter')(items,function (item) {
return item.match(ctrl.taggingLabel);
});
if ( tagItems.length > 0 ) {
tagItem = tagItems[0];
}
item = items[0];
// remove existing tag item if found (should only ever be one tag item)
if ( item !== undefined && items.length > 0 && tagItem ) {
hasTag = true;
items = items.slice(1,items.length);
stashArr = stashArr.slice(1,stashArr.length);
}
newItem = ctrl.search+' '+ctrl.taggingLabel;
if ( _findApproxDupe(ctrl.selected, ctrl.search) > -1 ) {
return;
}
// verify the the tag doesn't match the value of an existing item from
// the searched data set or the items already selected
if ( _findCaseInsensitiveDupe(stashArr.concat(ctrl.selected)) ) {
// if there is a tag from prev iteration, strip it / queue the change
// and return early
if ( hasTag ) {
items = stashArr;
$scope.$evalAsync( function () {
ctrl.activeIndex = 0;
ctrl.items = items;
});
}
return;
}
if ( _findCaseInsensitiveDupe(stashArr) ) {
// if there is a tag from prev iteration, strip it
if ( hasTag ) {
ctrl.items = stashArr.slice(1,stashArr.length);
}
return;
}
}
if ( hasTag ) dupeIndex = _findApproxDupe(ctrl.selected, newItem);
// dupe found, shave the first item
if ( dupeIndex > -1 ) {
items = items.slice(dupeIndex+1,items.length-1);
} else {
items = [];
items.push(newItem);
items = items.concat(stashArr);
}
$scope.$evalAsync( function () {
ctrl.activeIndex = 0;
ctrl.items = items;
});
}
});
_searchInput.on('tagged', function() {
$timeout(function() {
_resetSearchInput();
});
});
_searchInput.on('blur', function() {
$timeout(function() {
ctrl.activeMatchIndex = -1;
});
});
function _findCaseInsensitiveDupe(arr) {
if ( arr === undefined || ctrl.search === undefined ) {
return false;
}
var hasDupe = arr.filter( function (origItem) {
if ( ctrl.search.toUpperCase() === undefined || origItem === undefined ) {
return false;
}
return origItem.toUpperCase() === ctrl.search.toUpperCase();
}).length > 0;
return hasDupe;
}
function _findApproxDupe(haystack, needle) {
var dupeIndex = -1;
if(angular.isArray(haystack)) {
var tempArr = angular.copy(haystack);
for (var i = 0; i <tempArr.length; i++) {
// handle the simple string version of tagging
if ( ctrl.tagging.fct === undefined ) {
// search the array for the match
if ( tempArr[i]+' '+ctrl.taggingLabel === needle ) {
dupeIndex = i;
}
// handle the object tagging implementation
} else {
var mockObj = tempArr[i];
mockObj.isTag = true;
if ( angular.equals(mockObj, needle) ) {
dupeIndex = i;
}
}
}
}
return dupeIndex;
}
function _getCaretPosition(el) {
if(angular.isNumber(el.selectionStart)) return el.selectionStart;
// selectionStart is not supported in IE8 and we don't want hacky workarounds so we compromise
else return el.value.length;
}
// See https://github.com/ivaynberg/select2/blob/3.4.6/select2.js#L1431
function _ensureHighlightVisible() {
var container = $element.querySelectorAll('.ui-select-choices-content');
var choices = container.querySelectorAll('.ui-select-choices-row');
if (choices.length < 1) {
throw uiSelectMinErr('choices', "Expected multiple .ui-select-choices-row but got '{0}'.", choices.length);
}
if (ctrl.activeIndex < 0) {
return;
}
var highlighted = choices[ctrl.activeIndex];
var posY = highlighted.offsetTop + highlighted.clientHeight - container[0].scrollTop;
var height = container[0].offsetHeight;
if (posY > height) {
container[0].scrollTop += posY - height;
} else if (posY < highlighted.clientHeight) {
if (ctrl.isGrouped && ctrl.activeIndex === 0)
container[0].scrollTop = 0; //To make group header visible when going all the way up
else
container[0].scrollTop -= highlighted.clientHeight - posY;
}
}
$scope.$on('$destroy', function() {
_searchInput.off('keyup keydown tagged blur paste');
});
}]);