Water
Water

Reputation: 1182

AngularJS - how to set Select value based on specific JSON property?

I am beginner in AngularJS and I am having problems with setting the selected value of the ng-model of a Select.

Here is my data structure:

[{"ID":0,"Name":"G"},{"ID":1,"Name":"PG"}]

Here is my HTML:

<div class="col-md-8" ng-init="GetAllRatings()">
      <select ng-model="InputMovieRating" ng-options="rating.Name for rating in ratings"></select>
</div>

And I want to do this:

$scope.InputMovieRating = 'PG';

But it is not working. What I found that worked is to iterate through the ratings, and something like this:

    var selectedRating = $scope.ratings[0]; //default
    for (var i = 0; i < $scope.ratings.length; i++)
    {
        if($scope.ratings[i].Name == 'PG')
        {
            selectedRating = $scope.ratings[i];
        }
    }
    $scope.InputMovieRating = selectedRating;

That one works but I am thinking that it might be an incorrect way, and I am just doing something wrong with binding of ng-options.

Upvotes: 1

Views: 79

Answers (2)

NTP
NTP

Reputation: 4448

try the following

<div class="col-md-8" ng-init="GetAllRatings()">
  <select ng-model="InputMovieRating" ng-options="rating.Name as rating.Name for rating in ratings"></select>
</div>

if you have asynchronous data loading set the value of model

  $scope.InputMovieRating = "PG";

after data load is complete.

Demo

Upvotes: 1

Linoy
Linoy

Reputation: 1395

Might be you missed to assign an object to the property .What you added is just a value (PG)

$scope.InputMovieRating = {"ID":1,"Name":"PG"}

Upvotes: 0

Related Questions