AngularJS - 存储页面数据

时间:2015-02-12 14:12:26

标签: json angularjs storage

我想用本地存储或cookie存储我的数据。数据源是json,这个json有数据限制(每页10个数据)。所以我实施了一个"显示更多" function,当我点击一个按钮时加载其他jsons。

我的问题是我无法正确存储整个加载的数据。我尝试了不同的技术,但没有。

这是html:

<div ng-controller="MyCtrl">
    <div ng-repeat="item in items">
        <p>{{item.title}}</p>
    </div>
    <button ng-click="getItems()" ng-hide="items.length == 0">show more</button>
</div>

这是控制器:

app.controller('MyCtrl', function($scope, $http) {
    $scope.items = [];
    var page = 1;

    $scope.getItems = function () {
        var url = 'https://differentdomain.com/json&page=' + page++;

        $http({method: 'GET', url: url}).
            success(function (data, status, headers, config) {
                if (status == 200) {
                    $scope.items = $scope.items.concat(data.results);
                    // or other way
                    // $scope.items.push.apply($scope.items, data.results)
                } else {
                    console.error('Error happened while getting list.')
                }
            }).
            error(function (data, status, headers, config) {
                console.error('Error happened while getting the list.')
            });
    };

    $scope.getItems();
});

任何人都有想法,我怎样才能存储加载的数据?

2 个答案:

答案 0 :(得分:0)

上面应该可行,我假设每次点击按钮时都会加载10个。

您的问题似乎是如何在浏览器会话之间保留这些已加载的项目。如果是这样,我建议你看看:

https://github.com/goodeggs/angular-cached-resource

这会抽象出所有困难的部分,例如持久性和缓存检索,以便为您提供一致的API。

答案 1 :(得分:0)

如果您只想知道存储数据的热点,可以使用localStorage.setItem来保存数据,使用localStorage.getItem来检索这些数据。

最简单的实现是

app.controller('MyCtrl', function($scope, $http) {
    //retrieving saved object or init new array

    $scope.getItems = function () {
        //XXX if page is last one then return;
        //current page is basically num of objects divided by page size (10 in this case)
        var page = ($scope.items.length / 10) + 1;
        var url = 'https://differentdomain.com/json&page=' + page++;

        $http({method: 'GET', url: url}).
            success(function (data, status, headers, config) {
                if (status == 200) {
                    $scope.items = $scope.items.concat(data.results);
                    //saving current object
                    localStorage.setItem('items', JSON.stringify($scope.items));
                } else {
                    console.error('Error happened while getting list.')
                }
            }).
            error(function (data, status, headers, config) {
                console.error('Error happened while getting the list.')
            });
    };
    $scope.items = JSON.parse(localStorage.getItem('items')) || [];
    if (!$scope.items.length) $scope.getItems();

});
相关问题