DevMetal91
DevMetal91

Reputation: 315

Angular js select ng-model binding

i have a big problem with angularjs. Here is my code:

Controller:

function testCt($scope){
    $scope.types = [
        {name:'fruit',label:'To Fruit'},
        {name:'meat',label:'To Meat'},
        {name:'other',label:'To Other'}
    ];

    $scope.foods = [
        {name:'apple',type:'fruit'},
        {name:'raptor',type:'meat'}
    ];

    $scope.selected = null;
    $scope.selectFood = function(food) {
        $scope.selected = food;
    }
};

And the view:

<div ng-app ng-controller="testCt">
    <ul>
        <li ng-repeat="food in foods" ng-click="selectFood(food)">
            {{food.name}}
        </li>
    </ul>
    <select data-ng-model='selected' data-ng-options='t.name as t.label for t in types'></select>
    <br>
    {{selected.name}} <br> {{selected.type}}
</div>

The problem is, the angular js not binding to select element the food what i clicked. Here is the fiddle: http://jsfiddle.net/p7JJs/

When i choose one food from list, the select element not bind to type. Thank for help :)

Upvotes: 0

Views: 2468

Answers (3)

user3568303
user3568303

Reputation: 102

Try this:

Change Your controller function

From

   $scope.selectFood = function(food) {
   $scope.selected = food;
   }

To

   $scope.selectFood = function(food) {
   $scope.selected = food.type;
   }

It will work..

Upvotes: 0

3k-
3k-

Reputation: 2563

Did you try ngSelected? Here're the docs:

https://docs.angularjs.org/api/ng/directive/ngSelected

Upvotes: 0

nilsK
nilsK

Reputation: 4351

try this:

data-ng-options="t as t.label for t in types"

fiddle

you have to set t as reference, not t.name (no attributes name or type in t.name)

Upvotes: 3

Related Questions