jdk2588
jdk2588

Reputation: 792

Can I use an array for ng-options instead of an object?

If I have to use ng-options with a list instead of an object, how can I iterate over it ?

Here is the code for controller

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

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

  }
]);

Here is the HTML5 code, which gives me error

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

Upvotes: 0

Views: 78

Answers (2)

Jeff Ward
Jeff Ward

Reputation: 1119

What you actually want is something like this:

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

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

Plunker Example

Upvotes: 1

Diana Nassar
Diana Nassar

Reputation: 2303

EDIT

You are simply missing an s:

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

DEMO

Suppose you have an array records:

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

You can iterate over it using:

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

Basic syntax is: record.desiredValueToSave as record.descriptionText for record in records

DEMO

Upvotes: 0

Related Questions