AngularJS设置多选下拉列表的值

时间:2015-06-24 18:52:04

标签: javascript angularjs

我有一个多选下拉列表,在设置值时可以正常工作,但是一旦设置,我需要显示在更新表单中选择的内容。我的值存储在可通过REST访问的DB(SharePoint)中。以下是一个示例REST输出,其中包含多个我的数组ID:

"CatId": [
    18,
    80,
    84
],

这是我的select函数,包括从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>

2 个答案:

答案 0 :(得分:5)

编辑:在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。

fiddle

<强>过时:

您需要指向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);
    }
});

答案 1 :(得分:1)

尝试将ng-options更改为:

<select class="form-control" id="Event_Cat" data-ng-model="vm.selectedCategory" data-ng-options="opt.id as opt.label for opt in categoryValues | orderBy:'label'" required>
      <option style="display:none" value="">Select a Category</option>
</select>

在控制器中更改此行:

$scope.vm.selectedCategory = $scope.categoryValues[currentDetailIndex].id;

编辑多项选择:

<select class="form-control" id="Event_Cat" data-ng-model="selectedCategoriesIds" data-ng-options="opt.id as opt.label for opt in categoryValues | orderBy:'label'" required multiple>
      <option style="display:none" value="">Select a Category</option>
</select>

在您的控制器中,将您想要选择的项目添加到$ scope.selectedCategoriesIds,例如:

$scope.selectedCategoriesIds = [];
$scope.selectedCategoriesIds.push('18');
$scope.selectedCategoriesIds.push('80');