ng-model and ng-options not matching up?

17,069

Solution 1

In Angular, the model is the single source of truth.
This means that if you want a value selected (and bound to your ngModel) you need to assign it to the model:

<select ng-model="resources.type"
        ng-options="type.name as type.name for type in resourceList.types">
</select>

$scope.resources = {...};
$scope.resourceList = {
    ...
    types: [
        {name: 'resourcetype1'}, 
        {name: 'resourcetype2'},
        ...
    ]
};

// Set the model to the desired value
$scope.resources.type = $scope.resourceList.types[0].name;

See, also, this short demo.

Solution 2

You don't have to set your model's value to the reference object in resourceList. In fact, the accepted answer works fine without this line:

$scope.resources.type = $scope.resourceList.types[0].name;

How is it working? Thanks to the "as" notation in the ngOptions. Without the "as", the match is made on the full type element, which is an object, so the match is made on the reference's object, not the name's value. With the "as" the match is made on the element's property, name.

I've forked the plunker: http://plnkr.co/edit/kORfxGdsWBUlFWHXp6Ry?p=preview

Solution 3

in my case it didnt work since ngOptions was an array of integers and i was trying to set ngModal to string type (2the year 2014).

the solution is simple: parseInt function

Share:
17,069
Garuuk
Author by

Garuuk

Updated on June 11, 2022

Comments

  • Garuuk
    Garuuk about 2 years

    I have a method in my resources object that comes in as:

    resources.type

    otherstuff: 'more strings'
    type:'specifictype'
    morestuff: 'morestuff'
    

    The user can change this type with a dropdown / through another call that gets a list of all possible types which looks like resourceList.types which has a list of objects like this json

    types:
         [
             {name:'resourcetype1'}, 
             {name:'resourcetype2'},
             etc...
         ],
    

    my html looks like:

    <select ng-model="resources.type" ng-options="name.name for name in resourceList.types">
    </select>
    

    The select/drop down box populates with my resourceList.type stuff but when the page loads the ng-model doesn't set to the already selected resource type. It actually selects a blank entry at the top of the drop down when you click. Is angular picky about this? How can I get the ng-model to behave the way I want it to?

    I tried messing around with ng-options with the different ways of getting the repeat but I feel like this is more how angular connects the model. Does it just match the string to the ng-options list?

    Here's the plnkr as you can see it's not defaulting to type1

    http://plnkr.co/edit/NyWACtFQuyndR6CG8lpN?p=info