AngularJS(1.5.8)-如何直接从获取json对象的控制器中填充选择选项列表? [英] AngularJS (1.5.8) - How do I populate a select option list directly from within controller that gets a json object?
问题描述
我有一个AngularJS应用,我想从JSON结果中填充选择下拉列表.
I have an AngularJS app that I want to populate a select drop down list from a JSON result.
控制器代码获取json,但如何填充$ scope.states.
The controller code gets the json but how do I populate the $scope.states.
我的下拉菜单在提取时仍然为空,页面的分辨率未呈现.
My drop down remains empty on the fetch and the res of the page does not render.
$ scope.accountAddresses是带有各种数据的JSON容器.我只关心shippingState键.
$scope.accountAddresses is a JSON container with various data. My concern is only for the shippingState key.
HTML代码
<select name="shippingState" id="shippingState" ng-model="accountAddresses.shippingState" class="state form-control" size="1">
控制器JSON提取代码
$http.get( serviceBase + 'Assets/us-states.json').success(function(d){
$scope.states = d;
});
我尝试了ng-repeat="state in $scope.states"
,但是下拉菜单中没有任何数据(状态缩写).
I tried ng-repeat="state in $scope.states"
but I do not get any data (state abbreviations) in the drop down.
JSON示例数据
[
{
"name": "Alabama",
"abbreviation": "AL"
},
{
"name": "Alaska",
"abbreviation": "AK"
}]
如何使人口群体像以下html选项代码一样工作?
How do I get the population to work like the following html code of options?
<option value="AK">AK</option>
<option value="AL">AL</option>
编辑
使用以下代码
<select name="shippingState" id="shippingState" ng-model="accountAddresses.shippingState" ng-options ="s.abbreviation as s.name for s in states" class="state form-control" size="1">
我得到以下内容,但我需要删除字符串:"并添加标签
<option value="string:AL" label="Alabama">Alabama</option>
<option value="string:AK" label="Alaska">Alaska</option>
推荐答案
您应该使用 ng-options .
取决于您要显示的内容:
Depending on what you want to show:
<select ng-options="state as state.name for state in states track by state.abbreviation" ng-model="accountAddresses.shippingState"></select>
这篇关于AngularJS(1.5.8)-如何直接从获取json对象的控制器中填充选择选项列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!