我有一个多选下拉菜单,它在设置值时可以适本地发挥作用,但设置后,我需要在更新表单中显示已选择的内容。我的值存储在可通过 REST 访问的数据库 (SharePoint) 中。这是一个示例 REST 输出,其中包含我的数组的多个 ID:
"CatId": [
18,
80,
84
],
这是我的选择函数,包括从 REST 检索变量:
var currentCatValue = results.CatId;
$scope.categoryValues = [];
appCatList.query(function (categorydata) {
var categoryValues = categorydata.value; // Data is within an object of "value", so this pushes the server side array into the $scope array
// Foreach type, push values into types array
angular.forEach(categoryValues, function (categoryvalue, categorykey) {
$scope.categoryValues.push({
label: categoryvalue.Title,
value: categoryvalue.ID,
});
})
var currentDetailIndex = $scope.categoryValues.map(function (e) { return e.value; }).indexOf(currentCatValue);
$scope.vm.selectedCategory = $scope.categoryValues[currentDetailIndex];
});
这是我的 HTML:
<select class="form-control" id="Event_Cat" data-ng-model="vm.selectedCategory"
data-ng-options="opt as opt.label for opt in categoryValues | orderBy:'label'" required>
<option style="display:none" value="">Select a Category</option>
</select>
最佳答案
编辑: 在 ng-model 中使用 id(受 yvesmancera 启发)将大大降低复杂性 - 您不再需要预处理您的选项和输入数组,只需将其插入并完成!
<select multiple ng-model="currentCatValue" ng-options="opt.ID as opt.Title for opt in categoryValues">
$scope.currentCatValue = currentCatValue;
$scope.categoryValues = categoryValues;
注意:如果原始数据是一个对象,通常我们会将 ng-options 预填充到一个数组中以保留选项的顺序。但由于您使用 orderBy,您可以直接将对象用作 ng-options。
过时:
您需要在 ng-options 中指向同一个对象,以便它们在加载时被选中。
$scope.categoryValues = [];
$scope.vm.selectedCategory = [];
angular.forEach(categoryValues, function (categoryvalue, categorykey) {
var category = {
label: categoryvalue.Title,
value: categoryvalue.ID,
}
$scope.categoryValues.push(category);
if (currentCatValue.indexOf(parseInt(category.value)) != -1) {
$scope.vm.selectedCategory.push(category);
}
});
关于javascript - AngularJS 设置多选下拉列表的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31034652/