質問

Currently I am trying to load a selectbox using the ng-options directive.

However I am not able to change the value of the created options, it just goes from 0-3 while I want those values to be identical to the "eigenschap_id" I pass through.

So it should have values from 23-26 instead of 0-3

Where does it go wrong?

Here is the code that I am using.

Controller:

$scope.eigenschappen.game = categories.Game;

Jsonstring / object:

 [{"cat_id":6,"cat_name":"Game","eigenschap_name":"RPG","eigenschap_id":23},{"cat_id":6,"cat_name":"Game","eigenschap_name":"Strategie","eigenschap_id":24},{"cat_id":6,"cat_name":"Game","eigenschap_name":"Avontuur","eigenschap_id":25},{"cat_id":6,"cat_name":"Game","eigenschap_name":"Simulatie","eigenschap_id":26}]

Html View

<select data-ng-options="i.eigenschap_id as i.eigenschap_name for i in eigenschappen.game" ng-model="chosen"></select>

Generated html

<select ng-model="chosen" data-ng-options="i.eigenschap_id as i.eigenschap_name for i in eigenschappen.game" class="ng-pristine ng-valid">
    <option value="?" selected="selected"></option>
    <option value="0">RPG</option>
    <option value="1">Strategie</option>
    <option value="2">Avontuur</option>
    <option value="3">Simulatie</option>
</select>
役に立ちましたか?

解決

When Angular generates the HTML select options, the value attribute (of each option element) might not be what you would expect... it is set as follows: . when using array as the datasource, the value is set to the array index . when using object as the datasource, the value is set to the key/property name

When the the user selects one of the options, Angular uses the index (or key) to lookup the value in array (or object) -- that looked-up value is what the model is set to. (So, the model is not set to the value you see in the HTML! This causes a lot of confusion.)

E.g., for an array datasource, Angular will set the model value to the value in the array at the index specified by the selected option value parameter. If your datasource array is [ 2013, 2014, 2015], the generated HTML will have values of 0, 1, 2 for the options elements. If you select the 2nd item, Angular looks in array[1] to find the value 2014, which is what the model is then set to

Source:Mark RajCok comment on http://docs.angularjs.org/api/ng.directive:select

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top