简体   繁体   中英

How can I select an item from a select list after populating it?

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?

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM