我是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/

10-12 07:36
查看更多