Javascript,AngularJS和setTimeout函数

时间:2014-11-14 21:28:13

标签: javascript angularjs

我想在AngularJS中使用javascript setTimeout,每秒后计数值会增加:

<!DOCTYPE html>
<html>
    <head>
        <title>MyCount</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script type="text/javascript" src="js/angular.min.js"></script>
        <script type="text/javascript">

如何正确写作

    function myController($scope) {
        $scope.count = 1;
        $scope.delayInc = function () {
            $timeout(function () {
                $scope.count += 1;
            }, 1000);
        };
    }
</script>

计数不会保持为1?

        <h2>My Second Count: {{count}}</h2>
    </body>
</html>

谢谢

2 个答案:

答案 0 :(得分:2)

$ interval与此更相关:

<!doctype html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    </head>
    <body ng-app="plunker" ng-controller="MainCtrl">
        {{iterator}}
    </body>
    <script>
        var app = angular.module('plunker', []);

        app.controller('MainCtrl', ['$scope', '$interval', function($scope, $interval) {
            $scope.iterator = 1;
            var interval = $interval(function() {
                $scope.iterator++;
                if ($scope.iterator > 10) {
                    $interval.cancel(interval);
                }
            }, 1000);
        }]);
    </script>
</html>

答案 1 :(得分:1)

您的代码存在一些问题。首先,您正在定义delayInc()函数,但您永远不会调用它。因此,没有安排$ timeout。这需要在控制器中调用,或者你需要从某个事件启动它(例如在按钮上点击ng)。

其次,根据您的描述,听起来您希望它每秒递增一次。使用$ timeout只会增加一次 - 在调用delayInc()后一秒钟。

看看下面的方法,显示$ timeout工作以及使用$ interval来让它每秒都在进行:

<body ng-controller="MainCtrl">
  <p>Count (timeout): {{count}}!</p>
  <button ng-click="delayInc()">Start Delay Timer</button>
  <p></p>
  <p>Count2 (interval): {{count2}}!</p>
  <button ng-click="repeatInc()">Start Interval Counter</button>
</body>


app.controller('MainCtrl', function($scope, $timeout, $interval) {
  $scope.count = 1;
  $scope.count2 = 1;
  $scope.delayInc = function() {
    $timeout(function() {
      $scope.count += 1;
    }, 1000);
  };
  $scope.repeatInc = function() {
    $interval(function() {
      $scope.count2 += 1;
    }, 1000);
  }

这是Plunker,所有这些都在工作:http://plnkr.co/edit/c0EFB7Lbs6ZjJL5NQf86?p=preview