Angularjs 用 json 填充选择选项
Angularjs populate select options with json
我希望用基本 json 数组中的值填充选择选项。
我的例子是国家选择。 每个国家/地区都有一个 id 元素和一个名称以及我可以忽略的其他字段。 基本上我想说的是将一个值放在value=""
字段中,另一个值放在<option>tags</option>
网页代码段
<div ng-controller="DemoCtrl">
<p>populate select options with ajax</p>
<select id="Country" name="Country" class="form-control" size="10"
ng-model ="chooseCountries">
<option ng:repeat="country in chooseCountries" value="{{country.id}}">
{{country.name}}
</option>
</select>
</div>
JavaScript 片段
'use strict';
function DemoSelectCtrl($scope) {
$scope.chooseCountries=[
{countryId : 1, name : "France - Mainland", desc: "some description" },
{countryId : 3, name : "Gibraltar", desc: "some description"},
{countryId : 3, name : "Malta", desc: "some description"}
];
});
我把它放在一起 js 小提琴.. 我想我错过了什么
-
angular.module('ui.bootstrap.demo', ['ui.bootstrap'])
- 确保你有ui.bootstrap。阅读如何安装它 http://angular-ui.github.io/bootstrap/ - 这是您更新的 jsfiddle http://jsfiddle.net/e31k5e6L/1/
在上面的示例中,您缺少value
属性更改此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>
并查看示例单击此处
您错误地键入了 value
属性,请将其更改为 country.countryId
。
此外,ng-model
指令设置为单个 countryId 值(或国家/地区 ID 数组),而不是完整对象。
<select id="Country" name="Country" ng-model ="selectedValue">
<option ng:repeat="country in chooseCountries" value="{{country.countryId}}">
...
.JS:
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"}
];
});
用对象填充标准选择(您也可以使用 angular-ui-select)的最佳方法是使用 "ng-options" 指令和 "ng-repeat" 使用 "track by id" (参见 AngularJS 文档),这适用于 ng-model。这是如何使用它的示例:
<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"是在控制器中定义的"controllerAs"的情况下,如果直接使用$scope,则可以删除"vm"。
这是我发现填充选择字段的最佳方式。
相关文章:
- CKeditor:更改对话框中的默认选择选项
- 如何在从多选下拉列表中选择选项值时动态生成文本框
- AngularJs列表ng单击以选择选项转换
- 使用基于文本的 Jquery 选择选项
- 当选择值x时,Javascript需要在正确的位置显示文本区域,从而循环通过具有选择选项的表单
- 在php和mysql中选择选项.一旦选择了选项,就列出我的sql数据库数据
- 选择选项时如何显示警报
- 使用php动态更改选择选项
- 选择“选择选项”时显示文本.怎么做
- LEAFLET地图和带有选择选项的标记-ANGULARjs
- 使用js将动态内容添加到选择选项列表中
- 用于使用javascript循环选择选项
- AngularJS-选择选项并在函数中使用它
- 禁用/启用基于单选/选择选项所选Javascript的文本框
- 如何使用jQuery隐藏与选择选项相关的选择选项列表
- 选择选项是添加或删除事件
- 使用jQuery向“选择选项”添加默认属性
- 构建HTML选择字段并使用JavaScript数组选择选项
- 带有动态选择选项的Firefox html5验证异常
- 只有当Angular从资源对象检索数据时,才选择选项元素