gpt4 book ai didi

javascript - AngularJS 在用户离开的地方保持类别扩展

转载 作者:行者123 更新时间:2023-12-02 22:28:43 27 4
gpt4 key购买 nike

我是 angularJS 的新手。最近我一直在做一个 angularJS 项目。我使用 ng-template 和 ng-repeat 来制作多产品类别树。我添加了一个按钮来控制子类别是否展开。这是问题,当用户点击其他页面并点击返回类别页面时,如何使类别保持在用户离开的位置展开?

最佳答案

您可以将当前树状态保存到 HTML5 Localstorage 中。
为每个类别添加唯一的 id 并将其保存到本地存储中。

function saveCurrentState() {
const openedCategories = /* find the opened categories */;
// we injected $window in our controller.
$window.localStorage.setItem('openedCategories', openedCategories.join(','));
}

然后,当您加载页面时

/* to be run on the page load.*/
function retrieveOpenedCategories() {
// all the current categories, open or not.
const categories = /* get all the categories */;
// we retrive our category from the localStorage. With some code to handle if it's empty / null.
const openedCategories = ($window.localStorage.getItem('openedCategories') || "").split(',');
// check if we have categories that were opened. length of 0 will evaluate to false-y.
if(openedCategories.length) {
// we use map because we want to change every value from the original array.
categories = categories.map((category) => {
if(openedCategories.includes(category.id)) {
category.open = true;
}
return category;
});
}
}

/* we show our categories, somehow.*/

关于javascript - AngularJS 在用户离开的地方保持类别扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58977830/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com