Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  


Supporting multiselect in select2 / ui-select2 with angularJS
Angular JS has a new multiselect dropdown, but the last time I looked, it was buggy. Maybe those are fixed by now, but in the interim, I have been using the (now deprecated) select2.js with ui-select2.js as the angular wrapper.
In some cases this is buggy, but it is workable if you use it exactly as follows. By using it EXACTLY this way, it will work as you expect, with multi-select and angular data binding.
Skipping even ONE of these steps will cause the control to be buggy.

1. Ensure you have the latest versions. Earlier versions have bugs.
* Select2 4.0.4
* ui.select2 as of 11/1/2017
2. Assign data source in javascript: (here I use controller/ctrl in the controller-as syntax)
* controller.allTags = data.AllTags
3. Assign data values in javascript, ensuring you set to an empty array if values are null/not yet selected:
* controller.assignedTags = data.AssignedTags == null ? [] : data.AssignedTags;
4a. Use an ng-if to ensure your dropdown does NOT appear until values are loaded
4b. Use <option with ng-repeat instead of data-ng-options
4c. Ensure your dropdown has a model specified, even if you don't need it
5c. Ensure your data source holds an array of complex objects with properties bound to option value and text, otherwise you need to implement #6 or your databinding will not work correctly:
* <select ui-select2 multiple ng-if="ctrl.assignedTags != null"
ng-model="ctrl.assignedTags" style="width: 100%;">
<option ng-repeat="o in ctrl.allTags" value="{{o.LookUpName}}">{{o.LookUpName}}</option>
6. If you need to update the assigned values programmatically after the initial load (not on UI), you'll need to set them to null to hide the dropdown, and then put them back after a timeout to make it show again. This will cause the control to re-bind to your new source:
* controller.assignedTags = null;
* $timeout(function () {
controller.assignedTags = data.AssignedTags== null ? [] : data.AssignedTags;
}, 1);

Created By: amos 11/1/2017 3:34:41 PM
Updated: 11/2/2017 2:19:42 PM