Darwin Tech
Darwin Tech

Reputation: 18919

Prevent initial select option being blank in Angular

I have some simple angular code which renders a form and populates a select box with options from an array:

html:

<form class="form-horizontal">
  <div class="control-group">
      Title: <br />
      <input ng-model="new_project.title" type="text" id="title" class="form-control" placeholder="Title" >
      Created By: <br />
      <select data-ng-options="o.name for o in assignedToOptions" data-ng-model="new_project.created_by" id="created_by" class="form-control"></select>
  </div>
  ...
</form>

js:

$scope.getUsers = function () {
    ConcernService.list('users/').then(function(data) {
        $scope.users = data;
        // assign user list to select options
        $scope.assignedToOptions = [];
        i = 0;
        while (i < data.length) {
            $scope.assignedToOptions.push({ name: data[i].id, name: data[i].username });
            i++;
        };
    });
};

This all works fine, but Angular always places a blank option in the select field. What is the best way to eliminate the blank option?

Upvotes: 1

Views: 1197

Answers (1)

tasseKATT
tasseKATT

Reputation: 38490

To eliminate the blank option you need to make sure that the selects model has an initial value.

You can set it in the controller:

$scope.new_project = 
    {
      created_by: $scope.assignedToOptions[0]
    };

Or by adding the following attribute to the select element:

ng-init="new_project.created_by = assignedToOptions[0]"

Upvotes: 3

Related Questions