Angular.js:工厂在DOM中刷新页面之间存储值?

时间:2014-09-26 10:20:27

标签: angularjs

app.factory('theService', function (){
    var member = {
        myValue: false,
    };
    return myValue;
});

我有上面的代码,我想将其更改为存储并从DOM中回馈

app.factory('theService', function (){
    var member = {
        myValue: $window.sessionStorage["myValue"],
    };
    return myValue;
});

有效地在页面刷新之间保持boolean myValue的存储。任何其他想法如何在Angular中解决这个问题?我在auth服务中使用它。

1 个答案:

答案 0 :(得分:1)

您不应在服务中使用$ window。因为这使得测试服务变得非常困难。相反,您可以检索控制器中的值,然后将其存储在服务中。

此外,您不应该基于此MDN页面:https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage

建议使用setItem()getItem函数访问sessionStorage中的值:

myValue: $window.sessionStorage.getItem("myValue"),