Setting initial values of Angular-UI Select2 multiple directive
Asked Answered
B

2

21

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.

Bragdon answered 20/2, 2013 at 16:48 Comment(4)
plnkr doesnt even work. i hate thatSaransk
You might contemplate creating an accepted answer following ProLoser's advice.Wroth
If "Update 1" solved the problem, convert it to an answer and accept it.Rimester
I think "Update 1" is the answer, initSelection seems the correct way of doing itOliviero
I
8

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.

Impendent answered 16/8, 2013 at 5:0 Comment(0)
D
-1

Have you tried initialising your options as:

<option selected value="0">Name</option>
Dambro answered 19/3, 2015 at 5:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.