我试图使用AngularJS创建一个链接/级联的下拉列表(选择元素),但是我很难用我的对象属性过滤和更新“ selected”属性。
首次加载页面时,所选项目将被过滤并正确显示在下拉菜单中。更改父级下拉菜单后,子级选择项不会抓住已过滤列表中的第一个项,导致子级下拉项不会更新。
任何见解将不胜感激,请注意,我将父/子/孙子数组分开(而不是在子数组中),因为最终我将从SQL中的单独spocs /表中提取数据。如果有一种简单的方法可以在JSON中创建子数组,那么我愿意更改数据结构。
这是一个编码示例的链接
的HTML
<div ng-controller="dropdownCtrl" > <div> <select ng-model="selectedParentItem" ng-options="p.displayName for p in parentItems"> </select> </div> <div> <select ng-model="selectedChildItem" ng-options="c.displayName for c in filteredArray | filter:{parentId: selectedParentItem.id}"> </select> </div> <div> <select ng-model="selectedGrandChildItem" ng-options="g.displayName for g in grandChildItems | filter:{parentId: selectedChildItem.parentId}"> </select> </div> </div>
控制者
function dropdownCtrl($scope, filterFilter) { $scope.parentItems = [ { "id": 0, "displayName": "parent 00" }, { "id": 1, "displayName": "parent 01" }, { "id": 2, "displayName": "parent 02" } ]; $scope.selectedParentItem = $scope.parentItems[0]; $scope.childItems = [ { "id": 0, "displayName": "child0 of 00", "parentId": 0 }, { "id": 1, "displayName": "child1 of 00", "parentId": 0 }, { "id": 2, "displayName": "child2 of 00", "parentId": 0 }, { "id": 3, "displayName": "child0 of 01", "parentId": 1 }, { "id": 4, "displayName": "child1 of 01", "parentId": 1 }, { "id": 5, "displayName": "child0 of 02", "parentId": 2 } ]; $scope.filteredArray = []; $scope.$watch("parentId", function (newValue) { $scope.filteredArray = filterFilter($scope.childItems, newValue); $scope.selectedChildItem = $scope.filteredArray[0]; },true); $scope.grandChildItems = [ { "id": 0, "displayName": "grandChild0 of 00", "parentId": 0 }, { "id": 1, "displayName": "grandChild1 of 00", "parentId": 0 }, { "id": 2, "displayName": "grandChild2 of 00", "parentId": 0 }, { "id": 3, "displayName": "grandChild0 of 01", "parentId": 1 }, { "id": 4, "displayName": "grandChild1 of 01", "parentId": 1 }, { "id": 5, "displayName": "grandChild0 of 02", "parentId": 2 } ]; $scope.selectedGrandChildItem = $scope.grandChildItems[0]; }
您不需要对此进行监视。它比这更容易。注释掉过滤器,然后如下所示更改ng- option。请注意,您的最后一个过滤器看起来使用了错误的父ID(第三个下拉框是否与其父或祖父母有关?)
<select class="form-control" ng-model="selectedParentItem" ng-options="p.displayName for p in parentItems"> </select> <select class="form-control" ng-model="selectedChildItem" ng-options="c.displayName for c in childItems | filter:{parentId: selectedParentItem.id}"> </select> <select class="form-control" ng-model="selectedGrandChildItem" ng-options="g.displayName for g in grandChildItems | filter:{parentId: selectedChildItem.parentId}"> </select>