4

我正在尝试在 Angular 中实现级联下拉菜单。我认为由于绑定,它会自然而然地工作。见下文:

<select name="client" ng-model="selectedRequest.client" ng-options="c.name for c in clients track by c.id" required></select>
<select id="department" ng-model="selectedRequest.department" ng-options="d.defaultLabel for d in selectedRequest.client.departments track by d.id"></select>

加载视图后,它可以工作,我可以看到与绑定到客户端的部门匹配的部门。但是,每当 selectedRequest.client 更改时,部门下拉列表的源也应该更改,但它会变为空。

编辑

我已将子下拉列表更改为:

<select id="department" ng-model="selectedRequest.department" ng-options="d.defaultLabel for d in departments track by d.id | filter:{clientId: selectedRequest.client.id}"></select>

但这次它加载下拉列表中的所有部门,忽略过滤器。

** 编辑 2 **

更改为:

 <select name="client" ng-model="requestService.selectedRequest.client" ng-options="c as c.name for c in clients track by c.id" required></select>

 <select id="department" ng-model="requestService.selectedRequest.department" ng-options="d.defaultLabel for d in departments  | filter:{clientId: requestService.selectedRequest.client.id}"></select>

Now the source changes correctly when a client is selected. 然而,初始选择,即在启动时设置正确的部门,不起作用。那是因为我删除了 'track by id' 位。

4

2 回答 2

4

正确的方法是

 <select id="department" ng-model="selectedRequest.department" ng-options="d.defaultLabel for d in departments | filter:{clientId: selectedRequest.client.id} track by d.id "></select>

只是我没有把过滤器放在正确的地方......愚蠢的错误。

于 2013-10-16T18:47:31.877 回答
3

可能是您selectedRequest.client 没有引用clients数组中的同一对象。尝试这个:

JS:

function testController($scope) {
            $scope.clients = [
             { id: 1, name: "client1", departments: [{ id: 1, defaultLabel: 'department1' }, { id: 2, defaultLabel: 'department2'}] },
             { id: 2, name: "client2", departments: [{ id: 3, defaultLabel: 'department3' }, { id: 4, defaultLabel: 'department4'}] }
            ];

             $scope.selectedRequest = {};
             $scope.selectedRequest.client = $scope.clients[0];//Assign by object reference.
        }

HTML:

<div ng-controller="testController">
        <select name="client" ng-model="selectedRequest.client" ng-options="c.name for c in clients" required></select>
        <select id="department" ng-model="selectedRequest.department" ng-options="d.defaultLabel for d in selectedRequest.client.departments"></select>
    </div>

演示

我删除track by以使用默认值(按对象引用跟踪)并确保selectedRequest.client引用内部的对象clients

于 2013-10-11T14:05:02.327 回答