user3648646
user3648646

Reputation: 711

Binding Angularjs select items to model using property of item

I have a collection as follows:

$scope.TeamType = [
    {
        "name": "Beginner",
        "value": 0
    },
    {
        "name": "Novice",
        "value": 1
    },
    {
        "name": "Expert",
        "value": 2
    },
    {
        "name": "Masters",
        "value": 3
    }];

I also have a variable in my controller:

$scope.SelectedTeamType = 0;

I am trying to use these items in the following statement

<select ng-model="SelectedTeamType" ng-options="v as v.name for v in TeamType track by v.value"></select>

I would like the select to init with the corresponding value in the model and save the value to the model when select changes. I am not sure why the model SelectedTeamType is getting the entire object stored to it instead of the v.value and why it isnt initializing with beginner.

Upvotes: 0

Views: 45

Answers (1)

Satpal
Satpal

Reputation: 133403

As per comment I need to keep $scope.SelectedTeamType as an integer value

Use

<select 
    ng-model="SelectedTeamType" 
    ng-options="v.value as v.name for v in TeamType"
 ></select>

DEMO

Its storing object due to expression which you have provided in ngOptions.

You need to bind object, use

$scope.SelectedTeamType = $scope.TeamType[0];

better

$scope.SelectedTeamType = $scope.TeamType.filter(function(t) {
    return t.value == 0;
});

Upvotes: 1

Related Questions