yalkris
yalkris

Reputation: 2715

Angular select not displaying dropdown default

I have this below html

<select name="reason" class="form-control" ng-model="reasonSelected" 
ng-options="reason for reason in reasonList" required></select>

and in the beginning of my angular controller I have

$scope.reasonSelected = $scope.item.stsChangeReason;
$log.debug("$scope.reasonSelected = " + $scope.reasonSelected);

which is printing this below to console but still no default

LOG: $scope.reasonSelected = someValue

and in some other init function I have

$scope.reasonList = response;

If I do

$scope.reasonSelected = $scope.reasonList[0];

then I see a default value. Am I missing something obvious here?

Upvotes: 2

Views: 2201

Answers (3)

user12121234
user12121234

Reputation: 2569

This is a common mistake in AngularJS. In order to be set as a default, you need to make sure the reasonSelected scope variable is holding a reference to the desired reasonList scope array variable item (as you are seeing in your investigation).

The answer to your question is going to vary slightly based on whether you're working with an array of strings or objects or something else.

Edit: The problem is your ng-options arguments are incorrect. Use the select as label for value in array comprehensive expression. Note the as.

<select name="reason" class="form-control" ng-model="reasonSelected" 
    ng-options="reason as reason for reason in reasonList" required></select>

Assuming an array of strings: http://plnkr.co/edit/06c5pQ?p=preview

Upvotes: 3

yalkris
yalkris

Reputation: 2715

I did this and it worked

$scope.reasonSelectedSaved = $scope.item.stsChangeReason;

inside init function

$scope.reasonList = response;
$scope.reasonSelected = $scope.reasonSelectedSaved;

and using a watch I updated newly selected reason

$scope.$watch('reasonSelected', function () {
        $scope.item.stsChangeReason = $scope.reasonSelected;
    });

Upvotes: 0

wesww
wesww

Reputation: 2873

I'd have to see the data you're using for the ng-options, but it sounds like you don't have it initialized properly to the values you want. You may need to do something like ng-options="reason.id as reason.name for reason in reasonList", depending on your data, but from the sound of it doing $scope.reasonSelected = $scope.reasonList[0]; sounds pretty normal. Check out this other answer to the same question:

https://stackoverflow.com/a/17329854/1078450

Upvotes: 0

Related Questions