AngularJS中ng-show索引问题:动态切换可展开列表显示状态
Got it, let's sort out this expandable list issue you're facing with ng-show and $index. The core problem here is tracking which outer list item's inner content should be visible when you click its button—we just need a way to store and toggle the expansion state for each index.
Step 1: Add a state tracker in your controller
First, let's add a simple object to your controller (the vm instance) to keep track of which indices are expanded. This makes it easy to toggle states later:
// Inside your controller vm.expandedIndices = {}; // Stores boolean values for each index's expansion state vm.showLoc = function(index) { // Toggle the state for the clicked index—if it was expanded, collapse it, and vice versa vm.expandedIndices[index] = !vm.expandedIndices[index]; };
Step 2: Update your template to use the state tracker
Now modify your HTML to check the expandedIndices object in the ng-show directive. Since you have nested ng-repeats, we need to make sure we're referencing the outer index (not the inner one) to control visibility:
<div class="row" ng-repeat="list1 in Items track by $index"> <!-- Pass the outer loop's $index to the click handler --> <button ng-click="vm.showLoc($index)">Toggle Inner List {{$index + 1}}</button> <!-- Use $parent.$index to access the outer loop's index and check its expansion state --> <div class="row" ng-repeat="list2 in list1.listGroup track by $index" ng-show="vm.expandedIndices[$parent.$index]"> <div class="row" ng-repeat="listItem in list2.list track by $index"> {{listItem}} <!-- Replace with your actual list item content --> </div> </div> </div>
Quick Tips to Avoid Headaches:
- Avoid $index shadowing: Nested
ng-repeats reuse the$indexvariable, so using$parent.$indexensures we're targeting the outer list's index. If you want even more clarity, you can alias the outer index like this:ng-repeat="list1 in Items track by $index as outerIndex"—then useouterIndexinstead of$parent.$index. - Default expanded items: If you want certain items to start expanded, just set their index to
truein the controller:vm.expandedIndices[0] = true;will expand the first item on load. - Clean state management: Using an object for
expandedIndicesis efficient because we don't have to worry about array length or reordering issues—each index maps directly to its state.
This setup will let you click any button to toggle the visibility of its corresponding inner list, exactly as you need.
内容的提问来源于stack exchange,提问作者Belhanda

