Millenial2020
Millenial2020

Reputation: 2913

angular build an array

I have an app that everytime a user click that a tag, i want to the the id of the product click and put it in an array.

this is my view

<ion-view view-title='Products'>
<ion-content>
    <div class="row">
        <div class="col col-25" ng-repeat="row in products">
            <a href="#/main/tickets/{{row.productId}}" class="button button-block button-light">{{row.product}}<br/><small>{{row.price | currency}}</small></a>
        </div>
    </div>
</ion-content>

as you can see i get the row.productId of the product. now in my app.js i have this.

this is my app.js

.state('main.tickets', {
            url: '/tickets/:productId',
            views: {
                'tickets': {
                    templateUrl: 'templates/tickets.html',
                    controller:  'ticketsController'
                }
            }
        })

I'm getting the productId as an url parameter.

this is my controller.

.controller('ticketsController', function($scope, $localStorage, $stateParams){

var tickets = [];

tickets.push($stateParams.productId);

console.log(tickets);

})

the tickets array is suppose to get the id which is working, but everytime i click a new productId the array value resets, because it keeps on hitting the var tickets declaration. i want to somehow store all the productId in the tickets array, but i cannot find a way to do it without resetting the tickets arrray.

Upvotes: 0

Views: 68

Answers (1)

Ibrahim Rabbani
Ibrahim Rabbani

Reputation: 76

Your problem is that you are using a controller to store your tickets array. Each time you get to a ticket page, a new controller is created with a new $scope attached to it.

One simple solution to your problem is storing the tickets array in a service which will persist over the different pages.

.service('ticketModel',function() {
    var self = this;
    self.ticketArray = [];
}

.controller('ticketsController', function($scope,$statePrams,ticketModel) {
    ticketModel.ticketArray.push($stateParams.productId);
    console.log(ticketModel.ticketArray);
})

Upvotes: 1

Related Questions