0

Hi friends I'm new into angular and wanted to create a single page application.

My code working fine when create a list of products and when click on product I will land to detail page which is working absolutely fine but But now I want to show a another list which will show already viewed products.

I stared to dig out the solutions and came up with some idea to push ProductId in some array by using $routePrams which is working fine until user reload the page because after reload the page all the saved ProductId vanished from array. I also tried to save data to localstorage but failed and then came here for seeking help... Please check my code below and please suggest if their is any other way to crack this shit

controller.js

var myApp = angular.module('assignment', ['ngRoute']);



var viewedProducts = []; // created a global empty array
var uniqueNames = [];  // created second global empty array


myApp.config(['$routeProvider',function($routeProvider) {
  $routeProvider.when('/',{
      templateUrl : 'list/list.html'
    })
  .when('/:productId',{ // Passing productId 
    templateUrl : 'detail/detail.html'
  })

}])

myApp.service('myData', ['$http', function($http){
  return{
    itemList : function(){
      return $http({'method': 'GET', 'url' : 'js/data.json'}).then(function(response){
        return response.data;
      }, function(data){
        console.log(data);
      })
    }
  }
}])

myApp.controller('itemData', ['$scope','$http', 'myData', function($scope, $http, myData){

  myData.itemList().then(function(data){
    $scope.items = data;

  }, function(){
    console.log(data);
  })



}])

myApp.controller('details', ['$scope', '$http', '$routeParams', 'myData', function($scope, $http, $routeParams, myData){
  $scope.product = $routeParams; // Getting Product Id using $routeParams


  myData.itemList().then(function(data){


    angular.forEach(data, function(value, key){ 

      if(value.productId == $routeParams.productId) {
        $scope.product = value; 


        viewedProducts.push(value.productId);

        /*Trying to same data to localStorage*/
        localStorage.setItem('viewedItems', viewedProducts);
        var getViewed = localStorage.getItem('viewedItems');
        getViewed = getViewed.split(',')

        angular.forEach(getViewed, function(value, key){
            if(uniqueNames.indexOf(viewedProducts[key]) === -1) {
              uniqueNames.push(viewedProducts[key]);
            }
        });
      }

    });

  });

}])

myApp.controller('viewedProducts', ['$scope', '$http', '$routeParams' , 'myData', function($scope, $http, $routeParams, myData){

$scope.viewed = [];

  myData.itemList().then(function(data){
    //$scope.items = data
    angular.forEach(data, function(datavalue, datakey){

      angular.forEach(uniqueNames, function(value, key){
        if (datavalue.productId == uniqueNames[key] && datavalue.productId !== $routeParams.productId) {
          $scope.viewed.push(datavalue);
        }
      });

    });
  })

}])
Kamal
  • 2,140
  • 8
  • 33
  • 61

4 Answers4

0

$window.localStorage.setItem(key,value)

localStorage only supports strings, so you need to stringify your array with JSON.stringify().

Here is an in-depth solution

or you can use an angular module for this like angular-localstorage

Community
  • 1
  • 1
marton
  • 1,300
  • 8
  • 16
0

Its because localstorage only support string as Values.

Hence for storing the data use

localStorage.setItem('viewedItems', JSON.stringify(viewedProducts));

And for retriving the data use

var getViewed = JSON.parse(localStorage.getItem('viewedItems'));
ankur kushwaha
  • 458
  • 3
  • 9
0

Even i faced a similar issue like this and i used ngStorage which will provide both $localStorage and $sessionStorage services.

You can define it like this

controller('savedata', function($scope, $localStorage) {
  $scope.$storage = $localStorage.$default({
    x: 42
   });
});

Here is the Plnkr

Hope it works for you :)

Arun AK
  • 4,353
  • 2
  • 23
  • 46
0

Have updated your myData service to make use of storage, please check if this works,

myApp.service('myData', ['$http', '$window', '$q', '$timeout', function($http, $window, $q, $timeout) {
    var storage = $window.localStorage;

    return {
        itemList: function() {
            var deferred = $q.defer(),
                list = storage.getItem('item-list');

            if (list) {
                $timeout(function() {
                    deferred.resolve(angular.toJson(list));
                });
            } else {

                $http({ 'method': 'GET', 'url': 'js/data.json' })
                    .then(function(response) {
                            storage.setItem('item-list', angular.fromJson(response.data));
                            deferred.resolve(response.data);
                        },
                        function(data) {
                            console.log(data);
                            deferred.reject(data);
                        });
            }

            return deferred.promise;
        }
    }
}]);
Muthukannan Kanniappan
  • 2,080
  • 1
  • 16
  • 18