Scott
Scott

Reputation: 1003

Error with the initially selected option in a select

I am having trouble getting the initial option of a select box to be "selected" when the page loads.

View Code in Plunker

As you can see in the plunker, the selector is blank when it loads, however the deal model is initialized with a default category value. I'm sure I am missing something silly, but why does the select box not have an initial value?

View:

<p>Category: {{deal.category.name}}</p>

<select ng-model="deal.category" ng-options="category.name for category in categories"></select>

Controller:

app.controller("MyCtrl", function($scope) {

  // An object with a predefiend category.
  $scope.deal = {"category":{"_id":"1","name":"Music/Media","value":1}};

  // List of available categories
  $scope.categories = [{"_id":"1","name":"Music/Media","value":1},{"_id":"2","name":"Weather","value":2},{"_id":"3","name":"Navigation"}];
});


Update:

I created a simplified version, however the actual data is coming from a resources. So the controller actually looks a bit more like this:

$scope.deal = getDeal();
$scope.categories = Category.query();

However, the JSON in my example is exactly the same.

If I implement Davin Tryon's or Sza's examples then I would have to do something like this:

$scope.categories = Category.query(function() {
  for(var i = 0; i < $scope.categories.length; i++) {
    if($scope.categories[i]._id == $scope.deal.category._id) {
      $scope.deal.category = $scope.categories[i];
    }
  }
});

Which seems a little weird to me, is there another way?

Upvotes: 0

Views: 129

Answers (2)

zs2020
zs2020

Reputation: 54514

Since AngularJS needs to detect the equality of the model object with the object in the drop down list by reference, you need to use the same exact object as the pre-selected item rather than creating a new object.

This will fix the code:

$scope.categories = [{"_id":"1","name":"Music/Media","value":1},{"_id":"2","name":"Weather","value":2},{"_id":"3","name":"Navigation"}];
$scope.deal = {"category":$scope.categories[0]};

Upvotes: 1

Davin Tryon
Davin Tryon

Reputation: 67296

By default, ng-options will use the object reference, so you would have to select the category from the list.

So, you could change your controller to this:

  $scope.categories = [{"_id":"1","name":"Music/Media","value":1},{"_id":"2","name":"Weather","value":2},{"_id":"3","name":"Navigation"}];

  $scope.deal = $scope.categories[0];

Here is an updated plunker.

Upvotes: 0

Related Questions