在我的项目中,我需要从下拉列表中选择多个选项。我的代码看起来像这样:
//Controller
$scope.data = [{id: 1, Country: Zambia},
{id: 2, Country: United Kingdom}
{id: 3, Country: USA}]
$scope.selectedCountry = [];
//view
<select name="multipleSelect" id="multipleSelect" ng-model=" selectedCountry" multiple
ng-options="country.country as country.country for country in data"></select>
<h4> {{selectedCountry}}</h4>
上面的上下文有效,我可以从下拉列表中选择多个选项。这link帮我实现了这个目标。
问题所在。
现在我遇到的问题是,当我从下拉列表中选择选项时,我需要能够在selectedCountry数组中传递id和country,而不仅仅是国家/地区。所以例如在上面的上下文中,当你选择第一个国家时,传递给selectedCountry数组的信息将是这样的[“赞比亚”],但我真正想要的是这样的东西
[{id: 1, Country Zambia}].
为了解决这个问题,我尝试在视图中执行此操作:
<select name="multipleSelect" id="multipleSelect" ng-model=" selectedCountry" multiple
ng-options="{Id: country.Id, Country: country.country } as country.country for country in data"></select>
<h4> {{selectedCountry}}</h4>
运行良好,传递给selectedCountry数组的数据是{id: 1, Country: zambia}
之类的对象,但问题是我无法从下拉列表中选择多个选项,我只能选择1个选项。
我究竟做错了什么?什么是实现这一目标的最佳方法?
谢谢
答案 0 :(得分:1)
我在您的代码中发现了一些错误:
{"key":"value"}
相同。数组中的每个项目
必须用逗号分割。您可以使用以下代码的较短版本:country.Country for country in data
这样的事情:
(function() {
var app = angular.module("app", []);
app.controller("controller", ["$scope",
function($scope) {
$scope.selectedCountry = [];
$scope.data = [{
"id": 1,
"Country": "Zambia"
}, {
"id": 2,
"Country": "United Kingdom"
}, {
"id": 3,
"Country": "USA"
}];
}
]);
})();
&#13;
div {
margin: 2px;
}
.largeversion {
border: solid 1px #FF0000;
}
.shortversion {
border: solid 1px #005500;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<div data-ng-app="app">
<div data-ng-controller="controller">
<div class="largeversion">
<pre>ng-options="{Id: country.Id, Country: country.Country } as country.Country for country in data"</pre>
<select name="multipleSelect" id="multipleSelect" ng-model=" selectedCountry" multiple ng-options="{Id: country.Id, Country: country.Country } as country.Country for country in data"></select>
</div>
<div class="shortversion">
<pre>ng-options="country.Country for country in data"</pre>
<select name="multipleSelect" id="multipleSelect" ng-model=" selectedCountry" multiple ng-options="country.Country for country in data"></select>
</div>
<h4> {{selectedCountry}}</h4>
</div>
</div>
&#13;