This repository was archived by the owner on Sep 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathselect.js
executable file
·1687 lines (1448 loc) · 57.4 KB
/
select.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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @ngdoc module
* @name material.components.select
*/
/***************************************************
### TODO - POST RC1 ###
- [ ] Abstract placement logic in $mdSelect service to $mdMenu service
***************************************************/
var SELECT_EDGE_MARGIN = 8;
var selectNextId = 0;
var CHECKBOX_SELECTION_INDICATOR =
angular.element('<div class="md-container"><div class="md-icon"></div></div>');
angular.module('material.components.select', [
'material.core',
'material.components.backdrop'
])
.directive('mdSelect', SelectDirective)
.directive('mdSelectMenu', SelectMenuDirective)
.directive('mdOption', OptionDirective)
.directive('mdOptgroup', OptgroupDirective)
.directive('mdSelectHeader', SelectHeaderDirective)
.provider('$mdSelect', SelectProvider);
/**
* @ngdoc directive
* @name mdSelect
* @restrict E
* @module material.components.select
*
* @description Displays a select box, bound to an ng-model.
*
* When the select is required and uses a floating label, then the label will automatically contain
* an asterisk (`*`). This behavior can be disabled by using the `md-no-asterisk` attribute.
*
* By default, the select will display with an underline to match other form elements. This can be
* disabled by applying the `md-no-underline` CSS class.
*
* ### Option Params
*
* When applied, `md-option-empty` will mark the option as "empty" allowing the option to clear the
* select and put it back in it's default state. You may supply this attribute on any option you
* wish, however, it is automatically applied to an option whose `value` or `ng-value` are not
* defined.
*
* **Automatically Applied**
*
* - `<md-option>`
* - `<md-option value>`
* - `<md-option value="">`
* - `<md-option ng-value>`
* - `<md-option ng-value="">`
*
* **NOT Automatically Applied**
*
* - `<md-option ng-value="1">`
* - `<md-option ng-value="''">`
* - `<md-option ng-value="undefined">`
* - `<md-option value="undefined">` (this evaluates to the string `"undefined"`)
* - <code ng-non-bindable><md-option ng-value="{{someValueThatMightBeUndefined}}"></code>
*
* **Note:** A value of `undefined` ***is considered a valid value*** (and does not auto-apply this
* attribute) since you may wish this to be your "Not Available" or "None" option.
*
* **Note:** Using the `value` attribute (as opposed to `ng-value`) always evaluates to a string, so
* `value="null"` will require the test `ng-if="myValue != 'null'"` rather than `ng-if="!myValue"`.
*
* @param {expression} ng-model The model!
* @param {boolean=} multiple When set to true, allows for more than one option to be selected. The model is an array with the selected choices.
* @param {expression=} md-on-close Expression to be evaluated when the select is closed.
* @param {expression=} md-on-open Expression to be evaluated when opening the select.
* Will hide the select options and show a spinner until the evaluated promise resolves.
* @param {expression=} md-selected-text Expression to be evaluated that will return a string
* to be displayed as a placeholder in the select input box when it is closed. The value
* will be treated as *text* (not html).
* @param {expression=} md-selected-html Expression to be evaluated that will return a string
* to be displayed as a placeholder in the select input box when it is closed. The value
* will be treated as *html*. The value must either be explicitly marked as trustedHtml or
* the ngSanitize module must be loaded.
* @param {string=} placeholder Placeholder hint text.
* @param md-no-asterisk {boolean=} When set to true, an asterisk will not be appended to the
* floating label. **Note:** This attribute is only evaluated once; it is not watched.
* @param {string=} aria-label Optional label for accessibility. Only necessary if no placeholder or
* explicit label is present.
* @param {string=} md-container-class Class list to get applied to the `.md-select-menu-container`
* element (for custom styling).
*
* @usage
* With a placeholder (label and aria-label are added dynamically)
* <hljs lang="html">
* <md-input-container>
* <md-select
* ng-model="someModel"
* placeholder="Select a state">
* <md-option ng-value="opt" ng-repeat="opt in neighborhoods2">{{ opt }}</md-option>
* </md-select>
* </md-input-container>
* </hljs>
*
* With an explicit label
* <hljs lang="html">
* <md-input-container>
* <label>State</label>
* <md-select
* ng-model="someModel">
* <md-option ng-value="opt" ng-repeat="opt in neighborhoods2">{{ opt }}</md-option>
* </md-select>
* </md-input-container>
* </hljs>
*
* With a select-header
*
* When a developer needs to put more than just a text label in the
* md-select-menu, they should use the md-select-header.
* The user can put custom HTML inside of the header and style it to their liking.
* One common use case of this would be a sticky search bar.
*
* When using the md-select-header the labels that would previously be added to the
* OptGroupDirective are ignored.
*
* <hljs lang="html">
* <md-input-container>
* <md-select ng-model="someModel">
* <md-select-header>
* <span> Neighborhoods - </span>
* </md-select-header>
* <md-option ng-value="opt" ng-repeat="opt in neighborhoods2">{{ opt }}</md-option>
* </md-select>
* </md-input-container>
* </hljs>
*
* ## Selects and object equality
* When using a `md-select` to pick from a list of objects, it is important to realize how javascript handles
* equality. Consider the following example:
* <hljs lang="js">
* angular.controller('MyCtrl', function($scope) {
* $scope.users = [
* { id: 1, name: 'Bob' },
* { id: 2, name: 'Alice' },
* { id: 3, name: 'Steve' }
* ];
* $scope.selectedUser = { id: 1, name: 'Bob' };
* });
* </hljs>
* <hljs lang="html">
* <div ng-controller="MyCtrl">
* <md-select ng-model="selectedUser">
* <md-option ng-value="user" ng-repeat="user in users">{{ user.name }}</md-option>
* </md-select>
* </div>
* </hljs>
*
* At first one might expect that the select should be populated with "Bob" as the selected user. However,
* this is not true. To determine whether something is selected,
* `ngModelController` is looking at whether `$scope.selectedUser == (any user in $scope.users);`;
*
* Javascript's `==` operator does not check for deep equality (ie. that all properties
* on the object are the same), but instead whether the objects are *the same object in memory*.
* In this case, we have two instances of identical objects, but they exist in memory as unique
* entities. Because of this, the select will have no value populated for a selected user.
*
* To get around this, `ngModelController` provides a `track by` option that allows us to specify a different
* expression which will be used for the equality operator. As such, we can update our `html` to
* make use of this by specifying the `ng-model-options="{trackBy: '$value.id'}"` on the `md-select`
* element. This converts our equality expression to be
* `$scope.selectedUser.id == (any id in $scope.users.map(function(u) { return u.id; }));`
* which results in Bob being selected as desired.
*
* Working HTML:
* <hljs lang="html">
* <div ng-controller="MyCtrl">
* <md-select ng-model="selectedUser" ng-model-options="{trackBy: '$value.id'}">
* <md-option ng-value="user" ng-repeat="user in users">{{ user.name }}</md-option>
* </md-select>
* </div>
* </hljs>
*/
function SelectDirective($mdSelect, $mdUtil, $mdConstant, $mdTheming, $mdAria, $parse, $sce,
$injector) {
var keyCodes = $mdConstant.KEY_CODE;
var NAVIGATION_KEYS = [keyCodes.SPACE, keyCodes.ENTER, keyCodes.UP_ARROW, keyCodes.DOWN_ARROW];
return {
restrict: 'E',
require: ['^?mdInputContainer', 'mdSelect', 'ngModel', '?^form'],
compile: compile,
controller: function() {
} // empty placeholder controller to be initialized in link
};
function compile(element, attr) {
// add the select value that will hold our placeholder or selected option value
var valueEl = angular.element('<md-select-value><span></span></md-select-value>');
valueEl.append('<span class="md-select-icon" aria-hidden="true"></span>');
valueEl.addClass('md-select-value');
if (!valueEl[0].hasAttribute('id')) {
valueEl.attr('id', 'select_value_label_' + $mdUtil.nextUid());
}
// There's got to be an md-content inside. If there's not one, let's add it.
if (!element.find('md-content').length) {
element.append(angular.element('<md-content>').append(element.contents()));
}
// Add progress spinner for md-options-loading
if (attr.mdOnOpen) {
// Show progress indicator while loading async
// Use ng-hide for `display:none` so the indicator does not interfere with the options list
element
.find('md-content')
.prepend(angular.element(
'<div>' +
' <md-progress-circular md-mode="indeterminate" ng-if="$$loadingAsyncDone === false" md-diameter="25px"></md-progress-circular>' +
'</div>'
));
// Hide list [of item options] while loading async
element
.find('md-option')
.attr('ng-show', '$$loadingAsyncDone');
}
if (attr.name) {
var autofillClone = angular.element('<select class="md-visually-hidden">');
autofillClone.attr({
'name': attr.name,
'aria-hidden': 'true',
'tabindex': '-1'
});
var opts = element.find('md-option');
angular.forEach(opts, function(el) {
var newEl = angular.element('<option>' + el.innerHTML + '</option>');
if (el.hasAttribute('ng-value')) newEl.attr('ng-value', el.getAttribute('ng-value'));
else if (el.hasAttribute('value')) newEl.attr('value', el.getAttribute('value'));
autofillClone.append(newEl);
});
// Adds an extra option that will hold the selected value for the
// cases where the select is a part of a non-angular form. This can be done with a ng-model,
// however if the `md-option` is being `ng-repeat`-ed, AngularJS seems to insert a similar
// `option` node, but with a value of `? string: <value> ?` which would then get submitted.
// This also goes around having to prepend a dot to the name attribute.
autofillClone.append(
'<option ng-value="' + attr.ngModel + '" selected></option>'
);
element.parent().append(autofillClone);
}
var isMultiple = $mdUtil.parseAttributeBoolean(attr.multiple);
// Use everything that's left inside element.contents() as the contents of the menu
var multipleContent = isMultiple ? 'multiple' : '';
var selectTemplate = '' +
'<div class="md-select-menu-container" aria-hidden="true">' +
'<md-select-menu {0}>{1}</md-select-menu>' +
'</div>';
selectTemplate = $mdUtil.supplant(selectTemplate, [multipleContent, element.html()]);
element.empty().append(valueEl);
element.append(selectTemplate);
if(!attr.tabindex){
attr.$set('tabindex', 0);
}
return function postLink(scope, element, attr, ctrls) {
var untouched = true;
var isDisabled, ariaLabelBase;
var containerCtrl = ctrls[0];
var mdSelectCtrl = ctrls[1];
var ngModelCtrl = ctrls[2];
var formCtrl = ctrls[3];
// grab a reference to the select menu value label
var valueEl = element.find('md-select-value');
var isReadonly = angular.isDefined(attr.readonly);
var disableAsterisk = $mdUtil.parseAttributeBoolean(attr.mdNoAsterisk);
if (disableAsterisk) {
element.addClass('md-no-asterisk');
}
if (containerCtrl) {
var isErrorGetter = containerCtrl.isErrorGetter || function() {
return ngModelCtrl.$invalid && (ngModelCtrl.$touched || (formCtrl && formCtrl.$submitted));
};
if (containerCtrl.input) {
// We ignore inputs that are in the md-select-header (one
// case where this might be useful would be adding as searchbox)
if (element.find('md-select-header').find('input')[0] !== containerCtrl.input[0]) {
throw new Error("<md-input-container> can only have *one* child <input>, <textarea> or <select> element!");
}
}
containerCtrl.input = element;
if (!containerCtrl.label) {
$mdAria.expect(element, 'aria-label', element.attr('placeholder'));
}
scope.$watch(isErrorGetter, containerCtrl.setInvalid);
}
var selectContainer, selectScope, selectMenuCtrl;
findSelectContainer();
$mdTheming(element);
if (formCtrl && angular.isDefined(attr.multiple)) {
$mdUtil.nextTick(function() {
var hasModelValue = ngModelCtrl.$modelValue || ngModelCtrl.$viewValue;
if (hasModelValue) {
formCtrl.$setPristine();
}
});
}
var originalRender = ngModelCtrl.$render;
ngModelCtrl.$render = function() {
originalRender();
syncLabelText();
syncAriaLabel();
inputCheckValue();
};
attr.$observe('placeholder', ngModelCtrl.$render);
if (containerCtrl && containerCtrl.label) {
attr.$observe('required', function (value) {
// Toggle the md-required class on the input containers label, because the input container is automatically
// applying the asterisk indicator on the label.
containerCtrl.label.toggleClass('md-required', value && !disableAsterisk);
});
}
mdSelectCtrl.setLabelText = function(text) {
mdSelectCtrl.setIsPlaceholder(!text);
// Whether the select label has been given via user content rather than the internal
// template of <md-option>
var isSelectLabelFromUser = false;
if (attr.mdSelectedText && attr.mdSelectedHtml) {
throw Error('md-select cannot have both `md-selected-text` and `md-selected-html`');
}
if (attr.mdSelectedText || attr.mdSelectedHtml) {
text = $parse(attr.mdSelectedText || attr.mdSelectedHtml)(scope);
isSelectLabelFromUser = true;
} else if (!text) {
// Use placeholder attribute, otherwise fallback to the md-input-container label
var tmpPlaceholder = attr.placeholder ||
(containerCtrl && containerCtrl.label ? containerCtrl.label.text() : '');
text = tmpPlaceholder || '';
isSelectLabelFromUser = true;
}
var target = valueEl.children().eq(0);
if (attr.mdSelectedHtml) {
// Using getTrustedHtml will run the content through $sanitize if it is not already
// explicitly trusted. If the ngSanitize module is not loaded, this will
// *correctly* throw an sce error.
target.html($sce.getTrustedHtml(text));
} else if (isSelectLabelFromUser) {
target.text(text);
} else {
// If we've reached this point, the text is not user-provided.
target.html(text);
}
};
mdSelectCtrl.setIsPlaceholder = function(isPlaceholder) {
if (isPlaceholder) {
valueEl.addClass('md-select-placeholder');
if (containerCtrl && containerCtrl.label) {
containerCtrl.label.addClass('md-placeholder');
}
} else {
valueEl.removeClass('md-select-placeholder');
if (containerCtrl && containerCtrl.label) {
containerCtrl.label.removeClass('md-placeholder');
}
}
};
if (!isReadonly) {
element
.on('focus', function(ev) {
// Always focus the container (if we have one) so floating labels and other styles are
// applied properly
containerCtrl && containerCtrl.setFocused(true);
});
// Attach before ngModel's blur listener to stop propagation of blur event
// to prevent from setting $touched.
element.on('blur', function(event) {
if (untouched) {
untouched = false;
if (selectScope._mdSelectIsOpen) {
event.stopImmediatePropagation();
}
}
if (selectScope._mdSelectIsOpen) return;
containerCtrl && containerCtrl.setFocused(false);
inputCheckValue();
});
}
mdSelectCtrl.triggerClose = function() {
$parse(attr.mdOnClose)(scope);
};
scope.$$postDigest(function() {
initAriaLabel();
syncLabelText();
syncAriaLabel();
});
function initAriaLabel() {
var labelText = element.attr('aria-label') || element.attr('placeholder');
if (!labelText && containerCtrl && containerCtrl.label) {
labelText = containerCtrl.label.text();
}
ariaLabelBase = labelText;
$mdAria.expect(element, 'aria-label', labelText);
}
scope.$watch(function() {
return selectMenuCtrl.selectedLabels();
}, syncLabelText);
function syncLabelText() {
if (selectContainer) {
selectMenuCtrl = selectMenuCtrl || selectContainer.find('md-select-menu').controller('mdSelectMenu');
mdSelectCtrl.setLabelText(selectMenuCtrl.selectedLabels());
}
}
function syncAriaLabel() {
if (!ariaLabelBase) return;
var ariaLabels = selectMenuCtrl.selectedLabels({mode: 'aria'});
element.attr('aria-label', ariaLabels.length ? ariaLabelBase + ': ' + ariaLabels : ariaLabelBase);
}
var deregisterWatcher;
attr.$observe('ngMultiple', function(val) {
if (deregisterWatcher) deregisterWatcher();
var parser = $parse(val);
deregisterWatcher = scope.$watch(function() {
return parser(scope);
}, function(multiple, prevVal) {
if (multiple === undefined && prevVal === undefined) return; // assume compiler did a good job
if (multiple) {
element.attr('multiple', 'multiple');
} else {
element.removeAttr('multiple');
}
element.attr('aria-multiselectable', multiple ? 'true' : 'false');
if (selectContainer) {
selectMenuCtrl.setMultiple(multiple);
originalRender = ngModelCtrl.$render;
ngModelCtrl.$render = function() {
originalRender();
syncLabelText();
syncAriaLabel();
inputCheckValue();
};
ngModelCtrl.$render();
}
});
});
attr.$observe('disabled', function(disabled) {
if (angular.isString(disabled)) {
disabled = true;
}
// Prevent click event being registered twice
if (isDisabled !== undefined && isDisabled === disabled) {
return;
}
isDisabled = disabled;
if (disabled) {
element
.attr({'aria-disabled': 'true'})
.removeAttr('tabindex')
.off('click', openSelect)
.off('keydown', handleKeypress);
} else {
element
.attr({'tabindex': attr.tabindex, 'aria-disabled': 'false'})
.on('click', openSelect)
.on('keydown', handleKeypress);
}
});
if (!attr.hasOwnProperty('disabled') && !attr.hasOwnProperty('ngDisabled')) {
element.attr({'aria-disabled': 'false'});
element.on('click', openSelect);
element.on('keydown', handleKeypress);
}
var ariaAttrs = {
role: 'listbox',
'aria-expanded': 'false',
'aria-multiselectable': isMultiple && !attr.ngMultiple ? 'true' : 'false'
};
if (!element[0].hasAttribute('id')) {
ariaAttrs.id = 'select_' + $mdUtil.nextUid();
}
var containerId = 'select_container_' + $mdUtil.nextUid();
selectContainer.attr('id', containerId);
ariaAttrs['aria-owns'] = containerId;
element.attr(ariaAttrs);
scope.$on('$destroy', function() {
$mdSelect
.destroy()
.finally(function() {
if (containerCtrl) {
containerCtrl.setFocused(false);
containerCtrl.setHasValue(false);
containerCtrl.input = null;
}
ngModelCtrl.$setTouched();
});
});
function inputCheckValue() {
// The select counts as having a value if one or more options are selected,
// or if the input's validity state says it has bad input (eg string in a number input)
containerCtrl && containerCtrl.setHasValue(selectMenuCtrl.selectedLabels().length > 0 || (element[0].validity || {}).badInput);
}
function findSelectContainer() {
selectContainer = angular.element(
element[0].querySelector('.md-select-menu-container')
);
selectScope = scope;
if (attr.mdContainerClass) {
var value = selectContainer[0].getAttribute('class') + ' ' + attr.mdContainerClass;
selectContainer[0].setAttribute('class', value);
}
selectMenuCtrl = selectContainer.find('md-select-menu').controller('mdSelectMenu');
selectMenuCtrl.init(ngModelCtrl, attr.ngModel);
element.on('$destroy', function() {
selectContainer.remove();
});
}
function handleKeypress(e) {
if ($mdConstant.isNavigationKey(e)) {
// prevent page scrolling on interaction
e.preventDefault();
openSelect(e);
} else {
if (shouldHandleKey(e, $mdConstant)) {
e.preventDefault();
var node = selectMenuCtrl.optNodeForKeyboardSearch(e);
if (!node || node.hasAttribute('disabled')) return;
var optionCtrl = angular.element(node).controller('mdOption');
if (!selectMenuCtrl.isMultiple) {
selectMenuCtrl.deselect(Object.keys(selectMenuCtrl.selected)[0]);
}
selectMenuCtrl.select(optionCtrl.hashKey, optionCtrl.value);
selectMenuCtrl.refreshViewValue();
}
}
}
function openSelect() {
selectScope._mdSelectIsOpen = true;
element.attr('aria-expanded', 'true');
$mdSelect.show({
scope: selectScope,
preserveScope: true,
skipCompile: true,
element: selectContainer,
target: element[0],
selectCtrl: mdSelectCtrl,
preserveElement: true,
hasBackdrop: true,
loadingAsync: attr.mdOnOpen ? scope.$eval(attr.mdOnOpen) || true : false
}).finally(function() {
selectScope._mdSelectIsOpen = false;
element.focus();
element.attr('aria-expanded', 'false');
ngModelCtrl.$setTouched();
});
}
};
}
}
function SelectMenuDirective($parse, $mdUtil, $mdConstant, $mdTheming) {
// We want the scope to be set to 'false' so an isolated scope is not created
// which would interfere with the md-select-header's access to the
// parent scope.
return {
restrict: 'E',
require: ['mdSelectMenu'],
scope: false,
controller: SelectMenuController,
link: {pre: preLink}
};
// We use preLink instead of postLink to ensure that the select is initialized before
// its child options run postLink.
function preLink(scope, element, attr, ctrls) {
var selectCtrl = ctrls[0];
element.addClass('_md'); // private md component indicator for styling
$mdTheming(element);
element.on('click', clickListener);
element.on('keypress', keyListener);
function keyListener(e) {
if (e.keyCode == 13 || e.keyCode == 32) {
clickListener(e);
}
}
function clickListener(ev) {
var option = $mdUtil.getClosest(ev.target, 'md-option');
var optionCtrl = option && angular.element(option).data('$mdOptionController');
if (!option || !optionCtrl) return;
if (option.hasAttribute('disabled')) {
ev.stopImmediatePropagation();
return false;
}
var optionHashKey = selectCtrl.hashGetter(optionCtrl.value);
var isSelected = angular.isDefined(selectCtrl.selected[optionHashKey]);
scope.$apply(function() {
if (selectCtrl.isMultiple) {
if (isSelected) {
selectCtrl.deselect(optionHashKey);
} else {
selectCtrl.select(optionHashKey, optionCtrl.value);
}
} else {
if (!isSelected) {
selectCtrl.deselect(Object.keys(selectCtrl.selected)[0]);
selectCtrl.select(optionHashKey, optionCtrl.value);
}
}
selectCtrl.refreshViewValue();
});
}
}
function SelectMenuController($scope, $attrs, $element) {
var self = this;
self.isMultiple = angular.isDefined($attrs.multiple);
// selected is an object with keys matching all of the selected options' hashed values
self.selected = {};
// options is an object with keys matching every option's hash value,
// and values matching every option's controller.
self.options = {};
$scope.$watchCollection(function() {
return self.options;
}, function() {
self.ngModel.$render();
});
var deregisterCollectionWatch;
var defaultIsEmpty;
self.setMultiple = function(isMultiple) {
var ngModel = self.ngModel;
defaultIsEmpty = defaultIsEmpty || ngModel.$isEmpty;
self.isMultiple = isMultiple;
if (deregisterCollectionWatch) deregisterCollectionWatch();
if (self.isMultiple) {
ngModel.$validators['md-multiple'] = validateArray;
ngModel.$render = renderMultiple;
// watchCollection on the model because by default ngModel only watches the model's
// reference. This allowed the developer to also push and pop from their array.
$scope.$watchCollection(self.modelBinding, function(value) {
if (validateArray(value)) renderMultiple(value);
self.ngModel.$setPristine();
});
ngModel.$isEmpty = function(value) {
return !value || value.length === 0;
};
} else {
delete ngModel.$validators['md-multiple'];
ngModel.$render = renderSingular;
}
function validateArray(modelValue, viewValue) {
// If a value is truthy but not an array, reject it.
// If value is undefined/falsy, accept that it's an empty array.
return angular.isArray(modelValue || viewValue || []);
}
};
var searchStr = '';
var clearSearchTimeout, optNodes, optText;
var CLEAR_SEARCH_AFTER = 300;
self.optNodeForKeyboardSearch = function(e) {
clearSearchTimeout && clearTimeout(clearSearchTimeout);
clearSearchTimeout = setTimeout(function() {
clearSearchTimeout = undefined;
searchStr = '';
optText = undefined;
optNodes = undefined;
}, CLEAR_SEARCH_AFTER);
// Support 1-9 on numpad
var keyCode = e.keyCode - ($mdConstant.isNumPadKey(e) ? 48 : 0);
searchStr += String.fromCharCode(keyCode);
var search = new RegExp('^' + searchStr, 'i');
if (!optNodes) {
optNodes = $element.find('md-option');
optText = new Array(optNodes.length);
angular.forEach(optNodes, function(el, i) {
optText[i] = el.textContent.trim();
});
}
for (var i = 0; i < optText.length; ++i) {
if (search.test(optText[i])) {
return optNodes[i];
}
}
};
self.init = function(ngModel, binding) {
self.ngModel = ngModel;
self.modelBinding = binding;
// Setup a more robust version of isEmpty to ensure value is a valid option
self.ngModel.$isEmpty = function($viewValue) {
// We have to transform the viewValue into the hashKey, because otherwise the
// OptionCtrl may not exist. Developers may have specified a trackBy function.
return !self.options[self.hashGetter($viewValue)];
};
// Allow users to provide `ng-model="foo" ng-model-options="{trackBy: 'foo.id'}"` so
// that we can properly compare objects set on the model to the available options
var trackByOption = $mdUtil.getModelOption(ngModel, 'trackBy');
if (trackByOption) {
var trackByLocals = {};
var trackByParsed = $parse(trackByOption);
self.hashGetter = function(value, valueScope) {
trackByLocals.$value = value;
return trackByParsed(valueScope || $scope, trackByLocals);
};
// If the user doesn't provide a trackBy, we automatically generate an id for every
// value passed in
} else {
self.hashGetter = function getHashValue(value) {
if (angular.isObject(value)) {
return 'object_' + (value.$$mdSelectId || (value.$$mdSelectId = ++selectNextId));
}
return value;
};
}
self.setMultiple(self.isMultiple);
};
self.selectedLabels = function(opts) {
opts = opts || {};
var mode = opts.mode || 'html';
var selectedOptionEls = $mdUtil.nodesToArray($element[0].querySelectorAll('md-option[selected]'));
if (selectedOptionEls.length) {
var mapFn;
if (mode == 'html') {
// Map the given element to its innerHTML string. If the element has a child ripple
// container remove it from the HTML string, before returning the string.
mapFn = function(el) {
// If we do not have a `value` or `ng-value`, assume it is an empty option which clears the select
if (el.hasAttribute('md-option-empty')) {
return '';
}
var html = el.innerHTML;
// Remove the ripple container from the selected option, copying it would cause a CSP violation.
var rippleContainer = el.querySelector('.md-ripple-container');
if (rippleContainer) {
html = html.replace(rippleContainer.outerHTML, '');
}
// Remove the checkbox container, because it will cause the label to wrap inside of the placeholder.
// It should be not displayed inside of the label element.
var checkboxContainer = el.querySelector('.md-container');
if (checkboxContainer) {
html = html.replace(checkboxContainer.outerHTML, '');
}
return html;
};
} else if (mode == 'aria') {
mapFn = function(el) { return el.hasAttribute('aria-label') ? el.getAttribute('aria-label') : el.textContent; };
}
// Ensure there are no duplicates; see https://github.com/angular/material/issues/9442
return $mdUtil.uniq(selectedOptionEls.map(mapFn)).join(', ');
} else {
return '';
}
};
self.select = function(hashKey, hashedValue) {
var option = self.options[hashKey];
option && option.setSelected(true);
self.selected[hashKey] = hashedValue;
};
self.deselect = function(hashKey) {
var option = self.options[hashKey];
option && option.setSelected(false);
delete self.selected[hashKey];
};
self.addOption = function(hashKey, optionCtrl) {
if (angular.isDefined(self.options[hashKey])) {
throw new Error('Duplicate md-option values are not allowed in a select. ' +
'Duplicate value "' + optionCtrl.value + '" found.');
}
self.options[hashKey] = optionCtrl;
// If this option's value was already in our ngModel, go ahead and select it.
if (angular.isDefined(self.selected[hashKey])) {
self.select(hashKey, optionCtrl.value);
// When the current $modelValue of the ngModel Controller is using the same hash as
// the current option, which will be added, then we can be sure, that the validation
// of the option has occurred before the option was added properly.
// This means, that we have to manually trigger a new validation of the current option.
if (angular.isDefined(self.ngModel.$modelValue) && self.hashGetter(self.ngModel.$modelValue) === hashKey) {
self.ngModel.$validate();
}
self.refreshViewValue();
}
};
self.removeOption = function(hashKey) {
delete self.options[hashKey];
// Don't deselect an option when it's removed - the user's ngModel should be allowed
// to have values that do not match a currently available option.
};
self.refreshViewValue = function() {
var values = [];
var option;
for (var hashKey in self.selected) {
// If this hashKey has an associated option, push that option's value to the model.
if ((option = self.options[hashKey])) {
values.push(option.value);
} else {
// Otherwise, the given hashKey has no associated option, and we got it
// from an ngModel value at an earlier time. Push the unhashed value of
// this hashKey to the model.
// This allows the developer to put a value in the model that doesn't yet have
// an associated option.
values.push(self.selected[hashKey]);
}
}
var usingTrackBy = $mdUtil.getModelOption(self.ngModel, 'trackBy');
var newVal = self.isMultiple ? values : values[0];
var prevVal = self.ngModel.$modelValue;
if (usingTrackBy ? !angular.equals(prevVal, newVal) : (prevVal + '') !== newVal) {
self.ngModel.$setViewValue(newVal);
self.ngModel.$render();
}
};
function renderMultiple() {
var newSelectedValues = self.ngModel.$modelValue || self.ngModel.$viewValue || [];
if (!angular.isArray(newSelectedValues)) return;
var oldSelected = Object.keys(self.selected);
var newSelectedHashes = newSelectedValues.map(self.hashGetter);
var deselected = oldSelected.filter(function(hash) {
return newSelectedHashes.indexOf(hash) === -1;
});
deselected.forEach(self.deselect);
newSelectedHashes.forEach(function(hashKey, i) {
self.select(hashKey, newSelectedValues[i]);
});
}
function renderSingular() {
var value = self.ngModel.$viewValue || self.ngModel.$modelValue;
Object.keys(self.selected).forEach(self.deselect);
self.select(self.hashGetter(value), value);
}
}
}
function OptionDirective($mdButtonInkRipple, $mdUtil, $mdTheming) {
return {
restrict: 'E',
require: ['mdOption', '^^mdSelectMenu'],
controller: OptionController,
compile: compile
};
function compile(element, attr) {
// Manual transclusion to avoid the extra inner <span> that ng-transclude generates
element.append(angular.element('<div class="md-text">').append(element.contents()));
element.attr('tabindex', attr.tabindex || '0');
if (!hasDefinedValue(attr)) {
element.attr('md-option-empty', '');
}
return postLink;
}
function hasDefinedValue(attr) {
var value = attr.value;
var ngValue = attr.ngValue;
return value || ngValue;
}
function postLink(scope, element, attr, ctrls) {
var optionCtrl = ctrls[0];
var selectCtrl = ctrls[1];
$mdTheming(element);
if (selectCtrl.isMultiple) {
element.addClass('md-checkbox-enabled');
element.prepend(CHECKBOX_SELECTION_INDICATOR.clone());
}
if (angular.isDefined(attr.ngValue)) {
scope.$watch(attr.ngValue, setOptionValue);
} else if (angular.isDefined(attr.value)) {
setOptionValue(attr.value);
} else {
scope.$watch(function() {
return element.text().trim();
}, setOptionValue);
}
attr.$observe('disabled', function(disabled) {
if (disabled) {
element.attr('tabindex', '-1');
} else {
element.attr('tabindex', '0');
}
});
scope.$$postDigest(function() {
attr.$observe('selected', function(selected) {
if (!angular.isDefined(selected)) return;
if (typeof selected == 'string') selected = true;
if (selected) {
if (!selectCtrl.isMultiple) {
selectCtrl.deselect(Object.keys(selectCtrl.selected)[0]);
}
selectCtrl.select(optionCtrl.hashKey, optionCtrl.value);
} else {
selectCtrl.deselect(optionCtrl.hashKey);
}
selectCtrl.refreshViewValue();
});
});
$mdButtonInkRipple.attach(scope, element);
configureAria();