0

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 :)

3 Answers 3

3

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)

Sign up to request clarification or add additional context in comments.

Comments

0

Did you try ngSelected? Here're the docs:

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

Comments

0

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..

1 Comment

no it wont work :p (no access to selected.name for example ...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.