How to retain the last opened accordion in a group by invoking function in is-open attribute

眉间皱痕 提交于 2019-12-13 06:53:20

问题


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:


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.



来源:https://stackoverflow.com/questions/25631744/how-to-retain-the-last-opened-accordion-in-a-group-by-invoking-function-in-is-op

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!