AngularJS ng选项下拉列表

时间:2014-09-11 17:01:07

标签: javascript json angularjs

所以我想在angularJS中创建一个下拉选择菜单。我可以使用ng-repeat列出内容:

<table ng-table="tableParams" class="table">
<tr ng-repeat="food in foods">
<td data-title="'Name'">{{food.name}}</td>
</tr>
</table>

显示食物清单。我想把它变成一个选择。 但无论我尝试什么,它似乎都没有显示出来。 这是我到目前为止所做的工作:

<select id="food_select"class="form-control"
            ng-model="food"
            ng-options="item as item.name for item in food track by item.id">
<option value="">(Pick food)</option>
            </select>

以下是我获取数据的方式:

 function getFoodList() {
            FoodService.getFoods().then(function (_data) {

                $scope.foods= _data.foods;
                 console.log("foodlist"+JSON.stringify( $scope.foods));
            });
        }

这是一个json示例: “ID”: “540894f9b2a136082606e5f0”, “created_at”: “2014-09-04T16:36:09 + 0000”, “的updated_at”: “2014-09-04T16:36:09 + 0000”, “名”:“香蕉“

1 个答案:

答案 0 :(得分:2)

<强> JSFiddle Demo

option就像数组食物的索引值一样。

<强> HTML

<div ng-app>
    <div ng-controller="Ctrl">
        <select ng-options="food.option as food.name for food in foods" ng-init="index = 0" ng-model="option[index]">{{food.name}}</select>
    </div>
</div>

<强> JS

function Ctrl($scope) {
    $scope.foods = [{
        option: "1",
        name: "apple"
    }, {
        option: "2",
        name: "orange"
    }, {
        option: "3",
        name: "chicken"
    }];