我可以将数组用于ng-options而不是对象吗?

时间:2014-06-20 02:34:39

标签: angularjs

如果我必须将ng-options与列表而不是对象一起使用,我该如何迭代它呢?

这是控制器的代码

  angular.module("mainapp")
  .controller('NewController', [ "$scope", function ($scope, $modalInstance, data) {
    $scope.data = data;

    $scope.sex = ["Male", "Female"];

  }
]);

这是HTML5代码,它给了我错误

<div ng-controller="New Controller">
    <label class="select">
    <select ng-model="sex" ng-options="for s in sex" >
    <option value="" selected="" disabled="">Sex</option>
    </select> <i></i> </label>
</div>

2 个答案:

答案 0 :(得分:1)

你真正想要的是这样的:

$scope.sex = ["Male", "Female"];
$scope.selection = "";

<select ng-model="selection" ng-options="s for s in sex">

Plunker Example

答案 1 :(得分:0)

修改

你只是错过了一个s:

< ng-options="s for s in sex">

DEMO

假设您有一个数组records

 $scope.records = [{
        id: 1,
        value: "One",
    }, {
        id: 2,
        value: "Two",
    }, {
        id: 3,
        value: "Three",
    },{
        id: 4,
        value: "Four",
    }];

您可以使用以下方法迭代它:

<select ng-options="record.id as record.value for record in records" ng-model="output">
    <option value = "">- Select -</option>
</select>

基本语法是: record.desiredValueToSave as record.descriptionText用于记录中的记录

<强> DEMO