Angular js选择ng-model绑定

时间:2014-04-24 10:25:22

标签: angularjs

我对angularjs有一个很大的问题。 这是我的代码:

控制器:

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;
    }
};

观点:

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

问题是,角度js没有绑定选择元素我点击的食物。 这是小提琴: http://jsfiddle.net/p7JJs/

当我从列表中选择一种食物时,select元素不会绑定到类型。 感谢帮助:)

3 个答案:

答案 0 :(得分:3)

试试这个:

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

fiddle

你必须设置t作为参考,而不是t.name(没有属性名称或t.name中的类型)

答案 1 :(得分:0)

试试这个:

更改您的控制器功能

来自

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

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

它会起作用..

答案 2 :(得分:0)

你试过ngSelected吗?以下是文档:

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