How to retain the last opened accordion in a group

2019-09-06 17:22发布

I'm having accordion which is populated dynamically.

<accordion-group ng-repeat="data in dataList" is-open="isAccordionOpen(data.dataName)">
            <accordion-heading> 
                <span ng-click="openedAccordionGroup(data.dataName)" class="accordionSpan"><b>{{data.dataName}}</b>
                </span>
            </accordion-heading>
</accordion-group>

Here dataList keep on changing after 15 sec that means I'm populate dataList after regular inteval of 15sec. So i need to persist the last opened accordion group. DataList can be very hude. So i cant parse and modify it to avoid method invocation in is-open attribute.

In js file, 'm having following code.

$scope.openedAccordionName = '';
        $scope.isAccordionOpen = function(name){
            return  $scope.openedAccordionName === name;
        };
        $scope.openedAccordionGroup = function(name) {
            $scope.openedAccordionName = name;
        };

When I'm running it, its giving javascript error.

Error: [$compile:nonassign] Expression 'isAccordionOpen(data.dataName)' used with directive 'accordionGroup' is non-assignable!

What is wrong in above code?

1条回答
何必那么认真
2楼-- · 2019-09-06 17:37

You cannot really do that because angular is looking for a 2-way binding variable that it can assign to. You can easily maintain the last opened by using track by in your ng-repeat. With that what happens is angular will not recreate the DOM element, instead it will just update the existing element's scope which it identify based on what you are tracking by.

Here in the example i have an id for accordions so i am tracking it by id:-

<accordion-group ng-repeat="data in dataList  track by data.id" is-open="isOpen">

Plnkr

By default if no track by provided angular will add a unique id $$hashKey for the repeated elements and since you are refreshing as a whole list it will remove the elements from DOM and recreate them. Using track by you will get better performance improvement as well. You can provide any unique key as trackby value (event dataName if it is unique).

In this example you can see that the last accordion is retained opened even if you refresh the data since the isOpen is added on the child scope of repeated element even if you refresh the data if will only update the data based on the id, it wont recreate the accordion.

查看更多
登录 后发表回答