inspiredcoder
inspiredcoder

Reputation: 165

AngularJS <select> DOM markup

I'm curious when using ng-options and ng-model to set a selected item for the model why the Angular DOM markup isn't showing the correct value selected but is still displaying the correct value.

  $scope.myArray = [{ value: 'Yes' }, { value: 'No' }];

  $scope.cboModel.myArrayValSel = // Json pulled and value set from JS proxy call;

  <select ng-model="cboModel.myArrayValSel " ng-options="val.value as val.value for val in myArray " /> 

The DOM markup is rendering:

<option selected="selected" value="0" label="Yes">Yes</option>
<option value="1" label="No">No</option>

So, if the value comes back as 'No' for the object model property it is displaying this in the dropdown accordingly in the browser but I don't understand why it is not setting the selected="selected" attribute on the second item in the array. In this instance on

<option value="1" label="No">No</option>.  

If I was just concerned with the browser output this would be more of a curiosity but I am converting the HTML to a PDF. The PDF library is rendering the value that has the selected attribute set so there is an obvious disconnect between what is displayed in the browser and what is output in the PDF.

Upvotes: 2

Views: 293

Answers (1)

Phil
Phil

Reputation: 164795

The selected attribute would only effect the initial page load (based on the value assigned to $scope.cboModel.myArrayValSel).

If you want to see real values in the <option> value attributes, use a track by expression, eg

ng-options="val.value for val in myArray track by val.value"

Plunker


Note, for this to work, the bound ng-model must be an actual value from the array, not a scalar property (like 'Yes' or 'No').

You'll note in my example that I have

$scope.choice = $scope.myArray[0];

Upvotes: 3

Related Questions