Javascript Angularjs使用json填充选择选项
我希望用基本json数组中的值填充select选项 我举的例子是一个国家选择。每个国家都有一个id元素和一个名称以及我可以忽略的其他字段。基本上我想说的是,在value=字段中放置一个值,在标记之间放置另一个值 html代码段 我把它放在这里了。。我想我遗漏了一些内容如果您遗漏了键入的value属性,请将其更改为country.countryId 另外,将ng model指令设置为单个countryId值或国家ID数组,而不是完整对象Javascript Angularjs使用json填充选择选项,javascript,json,angularjs,select,populate,Javascript,Json,Angularjs,Select,Populate,我希望用基本json数组中的值填充select选项 我举的例子是一个国家选择。每个国家都有一个id元素和一个名称以及我可以忽略的其他字段。基本上我想说的是,在value=字段中放置一个值,在标记之间放置另一个值 html代码段 我把它放在这里了。。我想我遗漏了一些内容如果您遗漏了键入的value属性,请将其更改为country.countryId 另外,将ng model指令设置为单个countryId值或国家ID数组,而不是完整对象 <select id="Country" name="
<select id="Country" name="Country" ng-model ="selectedValue">
<option ng:repeat="country in chooseCountries" value="{{country.countryId}}">
...
在上面的示例中,缺少value属性change this value={{country.countryId}。试试这个
<select id="Country" name="Country" class="form-control" size="10" ng-model ="chooseCountries">
<option ng:repeat="country in chooseCountries" value="{{country.countryId}}">
{{country.name}}
</option>
</select>
看看这个例子
angular.module'ui.bootstrap.demo',['ui.bootstrap']-确保您有ui.bootstrap。阅读如何安装它
这是您更新的JSFIDLE
填充标准selectyou也可用于对象的最佳方法是使用ng options指令和ng repeat using track by id,这在ng模型中非常有效。这是一个如何使用它的示例:
<select id="select_field" name="select_field"
ng-model="vm.selectedCountry"
ng-options="country as country.name for country in vm.chooseCountries track by country.countryId">
<option value="">-- Select Country --</option>
</select>
我必须说vm是在控制器中定义的ControllerA的情况下,如果您直接使用$scope,您可以删除vm
这是我发现的填充选择字段的最佳方法 更改option value={{country.countryId}}的值,最好使用它。此行的作用是什么$scope.selectedCountry=angular.copy$scope.chooseCountries[0];这只是$scope.selectedCountry的默认值。如果不想使用默认值,可以删除此行。在本例中,angular.copy创建chooseCountries数组的第一个元素的副本。所以它的意思是$scope.selectedCountry={countryId:1,name:France-contain,desc:somedescription};
function DemoSelectCtrl($scope) {
$scope.selectedValue = 1;
$scope.chooseCountries=[
{countryId : 1, name : "France - Mainland", desc: "some description" },
{countryId : 3, name : "Gibraltar", desc: "some description"},
{countryId : 3, name : "Malta", desc: "some description"}
];
});
<select id="Country" name="Country" class="form-control" size="10" ng-model ="chooseCountries">
<option ng:repeat="country in chooseCountries" value="{{country.countryId}}">
{{country.name}}
</option>
</select>
<select id="select_field" name="select_field"
ng-model="vm.selectedCountry"
ng-options="country as country.name for country in vm.chooseCountries track by country.countryId">
<option value="">-- Select Country --</option>
</select>