1

I just need to store an array in localStorage and keep adding elements to that array so I could retrieve that stored array in my application. This must be a very simple thing to do with Angular Local Storage Module but it has got me troubling quite a bit, and I am hoping to get some help on this.

Following is the angular code I have that I am using to store a queries into localStorage using angular-local-storage module:

.factory('QueryService', ['localStorageService', function(localStorageService) {
        var queries = [];
        var factory = {};

        factory.addQuery = function(query) {
            queries.push(query);

            localStorageService.set('queries', queries);
            return localStorageService.get("queries");
        };
        return factory;
    }])

Every time I add a query to the queries array, I get only the last element added returned in the result. So basically, localStorageService.get("queries") is giving me the last element added to the queries array.

Could somebody please help me understand that why am I getting only the last element I am adding to the queries array returned?

EDIT: After each element I am adding to the queries array I am refreshing the browser.

4

1 回答 1

3

通常你不能用 localStorage 直接存储数组。但是 angular-local-storage 可以为您完成这项工作,如下所示:https ://github.com/grevory/angular-local-storage/blob/ed422c04764d4981a48f4c40859d65087b1b9838/src/angular-local-storage.js#L119

回答您的问题的线索是您在添加元素后刷新浏览器,因此查询数组确实被清理了。浏览器刷新实际上会清除所有 JavaScript 值和控制器,甚至整个 AngularJS 应用程序都会重新启动。

要使您的代码正常工作,您必须在控制器的第一行初始化查询数组:

.factory('QueryService', ['localStorageService', function(localStorageService) {
        var queries = localStorageService.get('queries') || [];
        var factory = {};

        factory.addQuery = function(query) {
            queries.push(query);

            localStorageService.set('queries', queries);
            return localStorageService.get("queries");
        };
        return factory;
    }])
于 2014-10-09T17:44:12.563 回答