角度 - 视图中的数组循环

时间:2015-12-09 13:52:42

标签: angularjs

我发现了与此相似的问题,但大多数问题最终都是关于ng-repeat或类似事情,这不是我在此之后的事情。

在我的情况下,我试图遍历一组消息,在视图中一次显示一条消息。以下是我的观点:

<div id="centerWrap" ng-init="looptyloop()">
<p>{{centerWrapMessage[loop.loop]}}</p>
</div>

我的控制器同时包含$scope.centerWrapMessage$scope.loop

我的控制器在这里:

$scope.centerWrapMessage = ["Click your category and then click your bread for more information.","If you intend to ship your order, please select a gift box","To add an item to your cart, hit the cart button"],
    $scope.loop = {
        loop: 0
    },
    $scope.looptyloop = function() {

    var i = 0;                    
function myLoop () {           
   setTimeout(function () {   
     i++; 
     $scope.loop.loop = i;
     if (i == $scope.centerWrapMessage.length - 1){
     i = -1;
     }
      if (i < $scope.centerWrapMessage.length) {            
         myLoop();             
      }                        
   }, 2222)
}

myLoop();        

},  

我可以在控制台日志中看到(当我把它放入时)$scope.loop.loop正在循环播放,但它在视图中永远不会改变。这是为什么?

谢谢!

2 个答案:

答案 0 :(得分:3)

由于你的myLoop函数超出了角度世界,所以每当你从外面改变$scope个对象时,你需要明确地调用摘要周期,即$ scope。$ apply为你做。还有其他方法可以使用$timeout$scope.$applyAsync,即在Angular 1.3中新引入。

使用$ scope。$ apply()或$ scope。$ applyAsync

function myLoop () {           
   setTimeout(function () {   
     i++; 
     $scope.$apply(function() { // Or use $scope.$applyAsync (Preferred)
        $scope.loop.loop = i;
     });
     if (i == $scope.centerWrapMessage.length - 1){
     i = -1;
     }
      if (i < $scope.centerWrapMessage.length) {            
         myLoop();             
      }                        
   }, 2222)
}

使用$ timeout

function myLoop () {           
    $timeout(function () {   
      i++; 
      $scope.loop.loop = i;
      if (i == $scope.centerWrapMessage.length - 1){
         i = -1;
      }
      if (i < $scope.centerWrapMessage.length) {            
          myLoop();             
      }                        
  }, 2222)
}
  

确保您已在控制器中注入$timeout服务。

答案 1 :(得分:0)

查看此plunker

var app = angular.module('plunker', []);

app.controller('MainCtrl', ['$scope', '$timeout', function($scope, $timeout) {
  $scope.centerWrapMessage = [
    "Click your category and then click your bread for more information.",
    "If you intend to ship your order, please select a gift box",
    "To add an item to your cart, hit the cart button"
  ];

  $scope.item = 'World';

  var i = 0;
  $scope.item = $scope.centerWrapMessage[i];

  function myLoop () {
    i++;
    $timeout(function() {
      console.log(i, $scope.centerWrapMessage[i]);
      $scope.item = $scope.centerWrapMessage[i];
    }, 0);

    if (i === $scope.centerWrapMessage.length - 1){
      i = 0;
    }
    $timeout(myLoop, 750);
  }

  myLoop();        

}]);