3

我有一系列国家:

var countriesList: [
                {name: "Israel", code: "IL"},
                {name: "India", code: "IN"},
                {name: "Andorra", code: "AD"}
            ]

以及一系列选定的国家:

    selectedCountries: [
                    {
                        country:"IL"
                    }
                ] 

我使用 select2 来选择国家。我从 ng-repeat 开始生成<options/>标签:

 <select
    id="countriesList"
    ui-select2
    multiple
    ng-model='data.selectedCountries'
    data-placeholder='Choose or Search for Countries'
    name='locations'
    ng-change='geoTargetingChanged()'>

       <option ng-repeat="country in data.countriesList" value="{{country.code}}">{{country.name}}</option>                
</select>

这种方法效果很好,但它导致表单$dirty在开始时是正确的。所以我开始使用 `ng-options- 机制(在阅读了这个答案之后):

<select
            id="countriesList"
            ui-select2
            multiple
            ng-model='data.selectedCountries'
            data-placeholder='Choose or Search for Countries'
            name='locations'
            ng-change='geoTargetingChanged()'
            ng-options="country.code as country.name for country in data.campaignSettings.countriesList">
           <option></option>
</select>

现在的问题是项目的值不是国家代码,而是它们在数组中的索引。

我错过了什么吗?

4

3 回答 3

3

这是一个笨蛋

我没有看到任何问题,尽管我确实将格式更改selectedCountries为国家代码数组 ( ["IL", ...]) 而不是您提供的数据结构 ( [{country:"IL", ...}])。

Angular 确实使用索引作为值生成选项,但ngModel将包含属性值。如果您使用 select 进行表单提交,您应该使用ngModelHTML 中的数据而不是 select 中的数据。如果您需要将页面上选择的数据放入表单中,您可以将选择的值ngModel放入隐藏的表单元素中。

于 2013-06-23T23:06:10.930 回答
0

如果您可以将所选项目作为您国家/地区列表中内容的镜像,如下所示:

$scope.data.selectedCountries = [$scope.data.countriesList[0]];

ng-options="country as country.name for country in data.countriesList">

然后这里是如何完成您需要的更新的 plunkr:http ://plnkr.co/edit/qE3SJm?p=preview

相反,如果您只需要国家/地区代码,则在将其分配到 selectedCountries 时,您必须引用它在国家/地区数组中的实际位置:

$scope.data.selectedCountries = [$scope.data.countriesList[0].code];

ng-options="country.code as country.name for country in data.countriesList">

其他 plunkr:http ://plnkr.co/edit/ysAatS?p=preview

于 2013-06-24T19:53:32.183 回答
0

尝试这个:

<select style="width: 100%" ui-select2="{multiple: true}" ng-model="countriesList" class="form-control select2"  multiple style="width:300px">
  <option></option>
  <option ng-repeat="country in countriesList" value="{{country}}">{{country}}</option>
</select>

假设结构就像提到的@rtcherry。

于 2014-02-10T16:47:38.370 回答