Pracede
Pracede

Reputation: 4361

Why my ng-options are not corrected generated?

I have json data generated in server. Data generated are :

[
   {"identifier":1,"data":{"name":"One"}},
   {"identifier":2,"data":{"name":"Two"}}
]

I want to create the following select :

<select  ng-model="mydata.identifier">
<option value="">Please choose option</option>
<option value="**0**">One</option>
<option value="**1**">Two</option>
</select>

Here is my code :

Angularjs controller:

$scope.initMyData =  function(){
    $http.get('getData')
    .success(function (data) {
                $scope.alldata= data;

    }); 
};

My html

 <select ng-model="mydata.identifier" ng-options="data.data.name for data in alldata">
          <option value="">Please choose option</option>
    </select>

Why value of my option are not correct ? What's not good with my code ? Thanks

Upvotes: 1

Views: 46

Answers (4)

Malkus
Malkus

Reputation: 3726

You can use the as annotation to tell angular what value to bind to ng-model

<select ng-model="mydata.identifier" 
      ng-options="data.identifier as data.data.name for data in alldata">
   <option value="">Please choose option</option>
</select>

Angular API reference

Upvotes: 0

Aditya Singh
Aditya Singh

Reputation: 16650

There are 2 issues in your code:

  1. You have missed 1 closing brace } at end of data object in data.
  2. You need to write your ng-options based on object.data format. E.g. value.data

<select ng-model="mydata.identifier" ng-options="value.data.name for value in allData"> <option value="">Please choose option</option> </select>

I have created a sample fiddle here

Upvotes: 1

Darshan P
Darshan P

Reputation: 2241

try this

<select ng-model="mydata.identifier" ng-options="data.data.name for data in alldata.data">
      <option value="">Please choose option</option>
</select>

Array should be like this

[  
   {"identifier":1,"data":{"name":"One"}},
   {"identifier":2,"data":{"name":"Two"}}
];

DEMO

Upvotes: 2

user2882597
user2882597

Reputation: 424

You are missing closing braces for one.

[
  {"identifier":1,"data":{"name":"One"},
  {"identifier":2,"data":{"name":"Two"}
]

Should be

[
  {"identifier":1,"data":{"name":"One"}},
  {"identifier":2,"data":{"name":"Two"}}
]

Upvotes: 2

Related Questions