Ionic Local storage将信息放入数组中

时间:2016-02-21 12:16:18

标签: ionic-framework angular-local-storage

这是代码

Controller.js

    <DOCTYPE html>
    <html>
    <body>
    <script type = "JavaScript">
    var myLights = ["red", "Yellow", "green"]
    </script>
    <script type = "CSS">
    red {
    border-radius: 50%;
    width: 200px; 
    height: 200px; 
    color: #ff0000;
    }
    </script>
    </body>
    </html>

Service.js

$scope.addFavorite = function (index) {
            $scope.temp = {
                id: index
            };

            $scope.dish = $localStorage.getObject('favorites', '{}');
            console.log($localStorage.get('favorites'));

            $localStorage.storeObject('favorites', JSON.stringify($scope.temp));

            var favorites = $localStorage.getObject('favorites');
            console.log(favorites);

            favoriteFactory.addToFavorites(index);
            $ionicListDelegate.closeOptionButtons();
        }

我想创建一个收藏夹功能,我想将标记的每个项目的ID放入一个数组中。

但是,它无法扩展数组并只更改值。

我在这里做错了吗?或者我可能在这里放错了方法?

提前谢谢!

1 个答案:

答案 0 :(得分:1)

我只是创建了存储对象的逻辑,你必须创建逻辑来从localstorage中删除对象。

<!DOCTYPE html>
<html ng-app="plunker">

<head>
    <meta charset="utf-8" />
    <title>AngularJS</title>

    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>

</head>
    <body ng-controller="MainCtrl">
        <div ng-repeat="item in items">
            {{item.item_name}} &nbsp; 
            <button ng-click="addFavorite(item.id)">Add to Favorite</button>
            <br><hr>
        </div>
    </body>
</html>

<script type="text/javascript">
    var app = angular.module('plunker', []);
    app.controller('MainCtrl', function($scope,$http) 
    {   
        $scope.items = [
            {id:1,item_name:'Apple'},
            {id:2,item_name:'Banana'},
            {id:3,item_name:'Grapes'},
        ]

        $scope.addFavorite = function (index) 
        {
            if(localStorage.getItem('favorites')!=undefined)
            {
                var old_favorite = JSON.parse(localStorage.getItem('favorites'));
                var obj = {index:index};
                old_favorite.push(obj);
                localStorage.setItem('favorites',JSON.stringify(old_favorite));
            }
            else
            {
                var obj = [{index:index}];
                localStorage.setItem('favorites',JSON.stringify(obj));
            }
        }
    });
</script>