多选字段

时间:2017-05-17 02:16:22

标签: angularjs

尝试在我的选择字段中预先选择多个值。

我的HTML

    <select multiple 
            data-ng-options="e.id for e in myElements"
            data-ng-model="mySelect">
    </select>

将数据放入选择框(工作正常)

    var elements = [
        { "id": "AAA" },
        { "id": "BBB" },
        { "id": "CCC" },
        { "id": "DDD" },
        { "id": "EEE" },
        { "id": "FFF" },
        { "id": "GGG" }
    ]
    $scope.myElements = elements; 

这不起作用

    var preselected = [
        { "id": "BBB" },
        { "id": "DDD" },
        { "id": "FFF" }
    ]
    $scope.mySelect = preselected;

这不起作用

    var preselected = [ "BBB", "DDD", "FFF" ]
    $scope.mySelect = preselected;

有人有任何想法吗?

1 个答案:

答案 0 :(得分:3)

您有两种选择:

1- 如果您希望将对象作为选定值PLUNKER

,请使用astrack by
ng-options="e as e.id for e in vm.elements track by e.id"

HTML

<select multiple
    ng-options="e as e.id for e in vm.elements track by e.id"
    ng-model="vm.selecetedValues">
</select>

CONTROLLER

function MainCtrl() {
    var vm = this;

    vm.elements  = [{ "id": "AAA" },{ "id": "BBB" },{ "id": "CCC" }];

    vm.selectedValues = [
        { "id": "AAA" },
        { "id": "CCC" }
    ];
}

2- 如果您希望字符串或数字作为选定值,则仅使用as语法PLUNKER

ng-options="e.id as e.name for e in elements"
  • 第一个参数e.id是所选选项的值
  • 第二个参数e.name是显示的值

在您的情况下:ng-options="e.id as e.id for e in elements"

HTML

<select multiple
    ng-options="e.id as e.id for e in vm.elements"
    ng-model="vm.selecetedValues">
</select>

CONTROLLER

function MainCtrl() {
    var vm = this;

    vm.elements  = [{ "id": "AAA" },{ "id": "BBB" },{ "id": "CCC" }];

    vm.selectedValues= [
        "BBB",
        "DDD"
    ];
}