Igle Igle - 4 months ago 19
AngularJS Question

ng-options doesn't work in select

I'm trying to implement a select in my angular app to show data about tv show episodes in a table.

In the select the user should be able to select one of the episodes.

I tried by

ng-repeat
the option elements, which worked. But when I try to set
ng-options
for the select, they seem to be not recognized.

Any idea, what I got wrong here?

Here is my html:

<div class="container-fluid full-height">
<div id="tabs_container" class="col-xs-12">


<div ng-app="seriesAnalyzer" ng-controller="configTableController">
<label>
Episode:
<select>
<option ng-repeat="episode in all_episodes | orderBy:['season_number','episode_number']">Season: {{episode.season_number}} Episode: {{episode.episode_number}}</option>
</select>
</label>

<!-- This is not working -->
<label>
Episode:
<select ng-options="episode.season_number for episode in all_episodes track by id">
<option value="">Please select an episode...</option>
</select>
</label>

<div ng-init="episode = episode_data">
<p>{{episode_data.episode_number}}</p>
<p>{{episode_data.season_number}}</p>
</div>

<table st-table="rowCollection" class="table table-striped">
<thead></thead>
<tbody>
<tr ng-repeat="scene in episode_data.configuration_matrix">
<td ng-repeat="values in scene track by $index" ng-style="set_color(values)" >{{values}}</td>
</tr>
</tbody>
</table>

</div>

<br>
</div>
</div>


And my controller:

seriesAnalyzer.controller('configTableController', function ($scope, $http) {

var req_url = 'http://localhost:8080/api/episodes';
$http.get(req_url)
.success(function (data) {
$scope.all_episodes = data;
console.log($scope.all_episodes);
})
.error(function (data) {
console.log('Error: ' + data);
});


$scope.update_season_number = function(){
console.log(val);
};

$scope.update_episode_number = function(){
console.log("Input changed");
};

var get_episode_data = function()
{
var req_url = 'http://localhost:8080/api/episodes?season_id=' + $scope.season_number + '&episode_id=' + $scope.episode_number
$http.get(req_url)
.success(function (data) {
$scope.episode_data = data;
})
.error(function (data) {
console.log('Error: ' + data);
});
};

....

Answer

try:

<select ng-options="episode as episode.season_number for episode in all_episodes track by episode.id" ng-model="selectedEpisode">
    <option value="">Please select an episode...</option>
</select>

More info can be found on the ng-options documentation

And here is an example jsfiddle as well (using Angular 1.5.1)

Also track by episode.id might not work for your version of Angular so you might have to remove it

In case you need both season number and episode number then do the following:

<select ng-options="episode.season_number + ' ' + episode.episode_number for episode in all_episodes track by episode.id" ng-model="selectedEpisode">
<option value="">Please select an episode...</option>
</select>
Comments