5

Currently I'm struggeling by setting the default value for a ng-options in angularjs. Can somebody help me?

I get the Options from a resource.

<select id="customer_country" ng-model="customer.country" ng-options="country.name for country in countries" style="width:230px;">
</select>

My current workaround is to set the default like this:

 $scope.countries = Country.query(function() {
    $scope.customer.country = $scope.countries[0];
 });

But I don't think its the best way to do it. I searched the internet but didn't find a good answer. How would you assign the default value?

Currently I need this that it don't has a null value. Also sometimes it won't have a null value and it shouldn't use the value that is in the model to update the model.

4 Answers 4

6

I encountered the same problem myself, and I believe that's the best way to go about it. That's also the way it's done in their documentation for the ng-options directive.

1

Here is an example from my code that I have been using.

HTML

<select ng-model="agent.id" ng-options="user.id as user.username for user in users"></select>

Controller

$scope.agent = {
    id: 2,
    address:4
};

It sets the dropdown value to 2, using the agents id to map to the user.id for each dropdown element. Don't know if that helps at all.

0
$scope.customer = {country: $scope.countries[0]};

or

$scope.customer.country = $scope.countries[0];
0

I noticed that if one of the options has the value equivalent to the model, angular assigns it as the default selected value.

Here is an example coffeescript code (note that value of currentPlant.status here is 'expired'):

Controller:

$scope.statusArr = [
  {value: 'active', display: 'Active'},
  {value: 'expired', display: 'Expired'}
]

$scope.currentPlant = CurrentPlants.get id : $routeParams.id

HTML:

<select class="form-control" ng-model="currentPlant.status" ng-options="status.value as status.display for status in statusArr">
        </select>

In this example, angular assigns 'expired' as the default selected option.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.