1

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Yes, just the 'PG' is intended. This is because the 'PG' itself comes from a different place. I just wrote it simply for easier explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.