值在AngularJS数组中被覆盖

时间:2016-04-25 13:54:41

标签: angularjs ionic-framework

我正在创建一个购物应用程序(Angular JS和Ionic)。每当我向购物车添加商品时,它都会覆盖前一个元素。以下是我的代码:

detail.html:

<ion-view view-title="DetailPage">
        <ion-content>
            <h4>
                Product Details
            </h4>
            <ion-view view-title="playlists">
                <ion-content>
                    <input type="button" ng-click="addToCart();" value="add cart" />
                </ion-content>
            </ion-view>

Controller.js:

.controller('detailsCtrl', function($scope, $stateParams) {

        var productname = $stateParams.playlistname;
        var arr = [];
        $scope.addToCart = function() {
            arr.push(productname);
            localStorage.setItem('arr', arr);


        })

如何处理元素的覆盖?

1 个答案:

答案 0 :(得分:2)

每次重新初始化阵列,然后将新阵列写入本地存储。您需要从本地存储中检索现有数组,然后将元素推送到它:

.controller('detailsCtrl', function($scope, $stateParams) {

        var productname = $stateParams.playlistname;
        // Get the product array from local storage if it exists
        // or initialise a new array.
        var arr = localStorage.getItem('arr') || [];
        $scope.addToCart = function() {
            arr.push(productname);
            localStorage.setItem('arr', arr);


        })