javascript - angularJS:页面刷新时更改图像。否则(如果不刷新)想在5秒内自动更改

标签 javascript jquery angularjs

这里创建了一个页面,在页面刷新图像发生变化。 来自这个问题Change Image when Page Refresh in angularJS 。现在我需要在 5 秒后更改图像自动,这意味着页面刷新或图像不想更改。我如何通过实现以下代码来解决这个问题。请帮助我...

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

 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  ;

这是我的 HTML

 <body>
   <div ng-app="app" ng-controller="ctrl">
     {{image}}
   <button ng-click="clear()">clear</button>
</div>
  </body>

这是正在工作的笨蛋 https://plnkr.co/edit/5ONenuXOwi54b2V2MXMW?p=preview

最佳答案

您可以使用超时功能在5秒后显示图像。

init();
function init(){
  for (var i=0;i<=$scope.data.length-1;i++) {

      setTime(i)
  }
}
function setTime(i){
  $timeout(function(){
    $scope.image = $scope.data[i].path;
    if (i == $scope.data.length-1) {
       init()
    }
  }, (5000 * i));
}

angular.module("app",[])
.controller("ctrl",function($scope,$timeout){
 
    $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"
  }]
    
    
  
 init();
 
  function init(){
    for (var i=0;i<=$scope.data.length-1;i++) {
      
        setTime(i)
    }
  }
  function setTime(i){
    $timeout(function(){
      $scope.image = $scope.data[i].path; 
      if (i == $scope.data.length-1) { 
          init();
      }
    }, (5000 * i));
  }
 
 $scope.clear = function(){
   debugger
   localStorage.removeItem("uIDs");
 }
 
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

     <div ng-app="app" ng-controller="ctrl">
       {{image}}
      <button ng-click="clear()">clear</button>
    </div>

关于javascript - angularJS:页面刷新时更改图像。否则(如果不刷新)想在5秒内自动更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43037658/

相关文章:

javascript - Node.js:停止执行除单个函数之外的所有代码?

javascript - 使用 JQuery 从嵌套 JSON 创建 HTML 表

jquery - 在 chrome bootstrap 中添加网站名称

javascript - 在 Angular 中,使用 async/await 时如何处理 promise 拒绝

javascript - 检查JSON响应数据是否为空

jquery - 结合 JQuery 和 AngularJS

javascript - 表格 HTML 溢出

javascript - 如何在脚本文件中使用 Razor View 中的模型?

c# - 页面方法多次回调

javascript - jQuery 卸载在 Chrome 中不起作用