AngularJS通过JSON填充下拉选择框选项

7
我希望您能将选择选项填充为基本json数组中的值,并使内容更加通俗易懂。 我们以国家选择为例。每个国家都有一个id元素和一个名称,还有其他我可以忽略的字段。 基本上,我想在value = ""字段中放置一个值,在<option> tags </option>之间放置另一个值。 html代码段:
<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 fiddle中。 我觉得我漏掉了什么。


1
更改选项 value="{{country.countryId}}" 的值。 - vamsikrishnamannem
1
最好使用ng-options - Wtower
4个回答

3
在上面的例子中,您缺少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>

并查看示例点击此处


3
  1. angular.module('ui.bootstrap.demo', ['ui.bootstrap']) - 确保您已安装了 ui.bootstrap。阅读如何安装它的 说明
  2. 这是您更新后的 jsfiddle 链接

这行代码是做什么的?$scope.selectedCountry = angular.copy($scope.chooseCountries[0]); - Robbo_UK
1
这只是$scope.selectedCountry的默认值(如果您不想使用默认值,可以删除此行)。在这种情况下,angular.copy创建了chooseCountries数组的第一个元素的副本。因此,这意味着$scope.selectedCountry = {countryId:1,name:“France-Mainland”,desc:“一些描述”}; - user2700840

2

您输错了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"}
    ];  

});

0

用最佳方式填充标准选择器(也可以使用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”。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接