Angularjs 用 json 填充选择选项

Angularjs populate select options with json

本文关键字:选择 选项 填充 json Angularjs      更新时间:2023-09-26

我希望用基本 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 小提琴.. 我想我错过了什么

  1. angular.module('ui.bootstrap.demo', ['ui.bootstrap']) - 确保你有ui.bootstrap。阅读如何安装它 http://angular-ui.github.io/bootstrap/
  2. 这是您更新的 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"。

这是我发现填充选择字段的最佳方式。