Skip to content Skip to sidebar Skip to footer

Change Image When Page Refresh In AngularJS

This is on of tough task that am facing in my school. am totally new to angularJs. i need to fetch one image out of all retrieved images from the database. And then when i refresh

Solution 1:

you can use localstorage to store the in in the first time. After you refresh the page increment the value and save it to the same local storage and so on.

run this Demo multiple time to see the id change.

controller

 if(!localStorage.getItem("uID")){
    var s = {"id":1};

    localStorage.setItem("uID", JSON.stringify(s))
  }
    $scope.data = [{
    "id": 1,
    "path": "Content/Banner/banner.jpg"
  },
  {
    "id": 2,
    "path": "Content/Banner/banner1.jpg"
  },
  {
    "id": 3,
    "path": "Content/Banner/banner2.jpg"
  },
  {
    "id": 4,
    "path": "Content/Banner/banner3.jpg"
  }]


 var item = localStorage.getItem("uID")
 item = JSON.parse(item);
 alert("Id = " + item.id)

 item.id = item.id +1  ;

 localStorage.setItem("uID", JSON.stringify(item))

 $scope.clear = function(){
   localStorage.removeItem("uID");
 }

updated

add this to check the image. check the demo again

 var item = localStorage.getItem("uID")
 item = JSON.parse(item); 

 var obj = $scope.data.find(function(o){
   return o.id === item.id
 }) 
 // add this lines 
 $scope.image =(obj)? obj.path : "invalid id";
 if(item.id == 4){
    localStorage.removeItem("uIDs");
    item.id = 0;
 }
 item.id = item.id +1  ;

Post a Comment for "Change Image When Page Refresh In AngularJS"