Search code examples
javascriptangularjsangular-uiangularjs-select2ui-select2

Angular ui-select2 with AJAX multiselect - retrieve final selection values as ids instead of json


Angular ui-select2 with AJAX multiselect - retrieve final selection values as ids instead of json

Problem statement

I want to use a tokeninput/chosen/select2 style of ui control to edit an array of ids in my model. That array of ids is the value of one property in a larger model I'm building an editor/form for. After editing the array of ids, when I submit the model to the server, I want that property to be submitted as an array of ids, not as an array of json objects.

When using angular's ui-select2 component, the contents of my property get replaced by an array of json objects. It's not clear how to undo that after editing is complete. I thought I might be using the wrong component, but all the threads seem to point back to using ui-select2 when doing this kind of thing with angular.

Explanation

The data model starts out with a 'myProp' property that's an array of ids:

{"myProp":["4","6"]}

The ui-select2 directive replaces those ids with json objects. Here is an example of what the model looks like with ui-select2 loaded. (live demo in this plunker: http://plnkr.co/edit/vEf1VwnRHNYdB9AuR9zO ):

{"myProp":[{"id":"4","text":"Label for 4"},{"id":"6","text":"Label for 6"},{"id":7,"text":"Seventh","color":"blue"}]}

When I save my model, I want this property to be submitted to the server as an array of ids, not an array of json objects. So basically I want to flatten the array back down to just ids instead of json objects. The select2 API provides a val method that would return this array of ids. How can/should I use it in the context of angular's ui-select2 component?

Caveat:I'm doing this multiple times on the page for multiple properties, so a hard-coded fix that is specific to the property will not work. It has to be something that happens automatically for any proptery I'm editing with select2

The Sample Code

(see code in this plunker: http://plnkr.co/edit/vEf1VwnRHNYdB9AuR9zO)


Solution

  • In the select2 directive, I tried changing instances of:

        elm.select2('val',
    

    to

        elm.select2('data',
    

    And this worked, but only once you'd added or removed an element. However, by adding

        elm.trigger('change'); 
    

    to the initSelection section, this triggers it on loading, which I think should give you your desired behaviour.

    Here's a plunker.