AngularJS循环不更新视图

AngularJS loops not updating the view

本文关键字:新视图 更新 循环 AngularJS      更新时间:2023-09-26

执行。。循环或While。。循环不会更新$scope变量。我试图显示循环递增时的进度。

我读过(http://jimhoskins.com/2012/12/17/angularjs-and-apply.html)如果没有通过事件或promise(如ng-click()事件或$http调用)检测到更改,我们需要使用$apply来强制更新。

我尝试过使用$apply强制更新,但这似乎没有改变任何事情。

我试过使用$timeout,但测试结果再次为阴性。

在下面的代码中,我尝试了三种不同的测试。最初我尝试了For。。循环,然后我试了一会儿。。循环,然后过一会儿。。循环使用$apply。这些测试是相互独立的,我把这三种测试都包括在内,只是为了向你展示我尝试过的变体。

var myApp = angular.module('myApp', []);
myApp.controller('CounterController', ['$scope', '$timeout', function($scope, $timeout) {

  $scope.counterMax = 5000;

  $scope.startCounter = function() {
    $scope.progress = 0;
    $scope.progress2 = 0;
    $scope.progress3 = 0;
    // for loop $scope test
    for (i = 0; i <= $scope.counterMax; i++) {
      $timeout(function() {
        $scope.progress = i;
      }, 500);
    }
    // while loop $scope test
    var x = 0;
    try {
      while (x < $scope.counterMax) {
        $timeout(function() {
          $scope.progress2 = x;
        }, 2);
        x++;
      }
    } catch (error) {
      console.log("Error: " + error);
    }

    // while loop $scope test with $apply
    x = 0;
    try {
      while (x < $scope.counterMax) {
        $timeout(function() {
          $scope.$apply(function() {
            $scope.progress3 = x;
          });
        }, 2000);
        x++;
      }
    } catch (error) {
      console.log("Error: " + error);
    }
  }
  $scope.startCounter();
}]);

视图

<div ng-controller="CounterController">
      <p>
        Depending on the value for the Counter Max, a loop will be made from zero to 
        the Counter Max value. 
        <br />
        The value in the Progress Indicators should increment gradually until the Counter Max value is reached.
        <br />
        Currently this is not happening. The Progress Indicators are only updated at the 
        end of the loop.
      </p>
      <p>
        Counter Max: <input type="text" ng-model="counterMax" ng-keyup="startCounter()"/>
      </p>
      <p>(for loop $scope test)<br />
      Progress Indicator 1: {{progress}}</p>
      <p>(while loop $scope test)<br />
      Progress Indicator 2: {{progress2}}</p>
      <p>(while loop $scope test with $apply)<br />
      Progress Indicator 3: {{progress3}}</p>
    </div>

你可以在plnkr上看到我的测试:http://plnkr.co/edit/Nl3GMy0DJNJ53PFObAq1?p=preview

注册超时的循环将始终非常快,并且由于在每次迭代中传递给$timeout的延迟是相同的,因此它们将同时触发,并且视图将显示为只更新一次。

如果希望视图中的数字逐渐增加,则传递给$timeout的延迟需要增加,如下面的示例所示。此外,由于i的值在每次迭代中都会永久更改,因此请确保根据其当前值递增progress变量。

for (i = 0; i <= $scope.counterMax; i++) {
  $timeout(function() {
    $scope.progress++;
  }, i);
}