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);
}
});
});
})
}])