Setting initial values of Angular-UI Select2 multiple directive

All we need is an easy explanation of the problem, so here it is.

I have a select2 directive for a multiple select of countries with a custom query to grab the data:

// Directive
<input ng-model="filters.countries" ui-select2="filters.countryOptions"
    data-placeholder="Choose a country...">

// filters.countryOptions
{ 
    multiple: true,
    query: function() { 
        get_list_of_countries(); 
    }
}

// Formatted data from remote source
[
    {id: 'US', text: 'United States'},
    {id: 'CA', text: 'Canada'} ...
]

I’m trying to set the initially selected values in my controller using:

$scope.filters.countries = [{id: 'US', text: 'United States'}];

This does correctly set the model, however this is happening before the select2 initialization has occurred. As I step through the remaining initialization code the input temporarily displays [Object] before finally blanking out $scope.filters.countries and the input, but it does not display the placeholder text in the input.

To get around this I’m using the following to reset the models’ initial value:

$scope.$on('$viewContentLoaded', function() {
    setTimeout(function() {
        $scope.filters.countries = [{id: 'US', text: 'United States'}];
    }, 100);
});

It seems really hackish to be using a setTimeout. Is there a better way that I’m missing?

Update 1

As requested by ProLoser here is a demo and github ticket.

Demo: http://plnkr.co/edit/DgpGyegQxVm7zH1dZIJZ?p=preview

GitHub Issue: https://github.com/angular-ui/angular-ui/issues/455

Following ProLoser’s advice I started using select2’s initSelection function:

initSelection : function (element, callback) {
  callback($(element).data('$ngModelController').$modelValue);
},

It does the trick but still feels like a workaround.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

As requested by ProLoser here is a demo and github ticket.

Demo: http://plnkr.co/edit/DgpGyegQxVm7zH1dZIJZ?p=preview

GitHub Issue: https://github.com/angular-ui/angular-ui/issues/455

Following ProLoser’s advice I started using select2’s initSelection function:

initSelection : function (element, callback) {
  callback($(element).data('$ngModelController').$modelValue);
},

It does the trick but still feels like a workaround.

Method 2

Have you tried initialising your options as:

<option selected value="0">Name</option>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply