aamiri
aamiri

Reputation: 2440

angular using ui-select2 to assign an object as a model property

Hypothetical example to illustrate a problem I am having using angular-UI select2. Let's say I have a screen where I want to edit a "game" model. A game, among other things has players. I want to be able to set the players via a select2 drop down menu. Here's some example code: app.js

$scope.getGamePromise().then(function(results) {
    $scope.game = results;
    console.log(game.players); //prints [{name:'Joe',age: 15},{name:'Sally',age:16}]
});

$scope.players = [
    {
        name: 'Joe',
        age: 15
    },
    {
        name: 'Fred',
        age: 14
    },
    {
        name: 'Sally',
        age: 16
    },
    {
        name: 'Lucy',
        age: 13
    }
]

view.html

<select ngModel="game.players" ui-select2 multiple>
    <option ng-repeat="player in players" value="player">{{ player.name }}</option>
</select>

When I want to save this 'game' object, I send the game object up to the server. The server is expecting game.players to be an array of objects. However, what is being sent up is a string. I am moderately familiar with angular, and completely new to select2. How can I get my select2 to set game.players as an array of objects instead of strings?

Upvotes: 2

Views: 2079

Answers (1)

Benjamin L.
Benjamin L.

Reputation: 178

I guess you find another solution or you don't have the problem anymore. Anyway I post it here:

Use

<input>

instead of

<select>

Example:

<input type="hidden" ui-select2="playersCfg" ng-model="players"/>

And following configuration:

$scope.playersCfg = {
        multiple: true,
        allowClear: true,
        data: { results: Player.query(), text: 'name' },
        formatResult: function(item) {
            return "<div class='select2-user-result'>" + item.name + "</div>";
        },
        formatSelection: function(item) {
            return item.name;
        }
    };

Player.query()

is a resource which returns a list of player containing a name (name) and an identifier (id)

Hope it would help somebody!

Upvotes: 1

Related Questions