0

I'm using AngularUI's ui-select2 directive with AJAX.

Here's what I've got in my view:

<label>Group: <input ng-model="group" ui-select2="select2GroupConfig"></label>

Here's what I have in my model:

$scope.select2GroupConfig = {
    ajax: {
        url: 'theURL',
        data: function (term, page)
        {
            return { q: term };
        },
        results: function (data, page)
        {
            return { results: data };
        }
    }
};

This works as expected.


My question: How can I update the value via the model?

I tried:

$scope.group = 'some group';

I also tried using an object:

$scope.group = { id: 32, text: 'some group'};

but that doesn't either work.

How do you update a select2 that uses AJAX, via the model?

2 Answers 2

1

Turns out you can set it to an object, but only after ui-select2 runs; I was trying to give it an initial value.

So, instead of using the regular model, you have to use select2's initSelection function:

$scope.group = 'Dummy Content';

$scope.select2GroupConfig.initSelection = function ( el, fn ) {
    fn({ id: 2, text: 'Some group' });
}

Note that you have to give the input an initial value, otherwise initSelection is never called. That's why I'm just setting it to some dummy content.


This works, but it feels like a hack.

Does anybody have any better ideas?

Sign up to request clarification or add additional context in comments.

1 Comment

"Note that you have to give the input an initial value" I've seen this comment in lots of places, but how does one go about providing an initial value. I've tried setting it via ng-model but that doesn't seem to trigger initSelection
0

If you have initSelection setup, you can pass just the ID and the directive will pull up the entire row object.

This will also allow you to set the value when the page loads to just the ID too.

If you don't want to use initSelection you can set the entire row (object) as the value and select2 will update accordingly. It all depends on your use-case however.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.