我正在尝试在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>
现在,当选择客户端时,源会正确更改。但是,初始选择,即在启动时设置正确的部门,不起作用。那是因为我删除了'id by id'位。
答案 0 :(得分: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>
只是我没有把过滤器放在正确的地方......愚蠢的错误。
答案 1 :(得分: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
内的对象