Handle open/collapse events of Accordion in Angular

后端 未结 7 1399
猫巷女王i
猫巷女王i 2020-11-29 02:04

If I have this code:


      {{group.content}}

         


        
7条回答
  •  隐瞒了意图╮
    2020-11-29 02:21

    Here's a solution inspired by kjv's answer, which easily tracks which accordion element is open. I found difficult getting ng-click to work on the accordion heading, though surrounding the element in a tag and adding the ng-click to that worked fine.

    Another problem I encountered was, although the accordion elements were added to the page programmatically, the content was not. When I tried loading the content using Angular directives(ie. {{path}}) linked to a $scope variable I would be hit with undefined, hence the use of the bellow method which populates the accordion content using the ID div embedded within.

    Controller:

        //initialise the open state to false
        $scope.routeDescriptors[index].openState == false
    
        function opened(index) 
        {
            //we need to track what state the accordion is in
            if ($scope.routeDescriptors[index].openState == true){   //close an accordion
                $scope.routeDescriptors[index].openState == false
            } else {    //open an accordion
                //if the user clicks on another accordion element
                //then the open element will be closed, so this will handle it
                if (typeof $scope.previousAccordionIndex !== 'undefined') {
                    $scope.routeDescriptors[$scope.previousAccordionIndex].openState = false;
                }
                $scope.previousAccordionIndex = index;
                $scope.routeDescriptors[index].openState = true;
        }
    
        function populateDiv(id)
        {
            for (var x = 0; x < $scope.routeDescriptors.length; x++)
            {
                $("#_x" + x).html($scope.routeDescriptors[x]);
            }
        }
    

    HTML:

            
    route {{$index}}

提交回复
热议问题