Reputation: 24562
I have the following HTML:
<span>SubTopic {{ modal.option.sSubTopic }}</span>
<select data-ng-model="modal.option.sSubTopic"
data-ng-options="item.id as item.name for item in modal.option.subTopics">
</select>
In my controller
$http.get(url, { cache: us.oneDayCache })
.success(function (data) {
$scope.modal.option.subTopics = data;
$scope.modal.option.sSubTopic = "2";
})
After the get the {{ }} value is set to 2 but the 2nd item of my select is not selected.
Is there something wrong with the way I am doing this?
Upvotes: 0
Views: 66
Reputation: 25726
You are specifying the value of the field to be the id
of the item with item.id as
in the ngOptions
. The model value needs to match the value of the data
id
you want selected. If you want the second object, it would be data[1].id
$http.get(url, { cache: us.oneDayCache })
.success(function (data) {
$scope.modal.option.subTopics = data;
$scope.modal.option.sSubTopic = data[1].id;
});
Demo: http://jsfiddle.net/TheSharpieOne/gteX9/2/
Upvotes: 1
Reputation: 306
The data-ng-model contains the model in which the selected value will be stored. In your case this would mean you'd store the selected value in 2. That doesn't seem right. Perhaps you could try something like:
<select ng-model="selectedItem" ng-options="item.id as item.name for item in modal.options.subTopics"></select>
<pre>{{selectedItem}}</pre>
$scope.selectedItem contains your selected item. Now you want to select the second item in your data object. You could do that by doing this in your controller:
$http.get(url, { cache: us.oneDayCache })
.success(function (data) {
$scope.modal.option.subTopics = data;
$scope.selectedItem = data[1];
})
Wasn't able to test it here, but it should work.
Upvotes: 0