javascript window.setInterval 不适用于 angularjs

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31207513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:27:22  来源:igfitidea点击:

window.setInterval not working on angularjs

javascriptangularjs

提问by simi kaur

I have this small piece of code that uses setIntervalmethod:

我有一小段使用setInterval方法的代码:

function MyController($scope) {
    $scope.clock = new Date();
    var updateClock = function() {
        $scope.clock = new Date();
    };
    setInterval(updateClock, 1000);
};

and html as follows:

和 html 如下:

<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>
</head>
<body>
    <div ng-controller="MyController">
        <h1>Hello {{ clock }}!</h1>
    </div>
    <script type="text/javascript" src="script.js"></script>
</body>
</html>

However, setIntervalin MyControllerdoes not update time. Where possibly is wrong here ?

但是,setIntervalMyController不更新时间。这里可能哪里错了?

It works this way according to a book :

根据一本书,它是这样工作的:

function MyController($scope) {
    $scope.clock = new Date();
    var updateClock = function() {
        $scope.clock = new Date();
    };
    setInterval(function() {
        $scope.$apply(updateClock);
    }, 1000);
    updateClock();
};

Why is that and what goes wrong without using @scope.$apply ?

为什么会这样,不使用 @scope.$apply 会出什么问题?

回答by Tom

Use the angular $intervalservice.

使用 angular $interval服务。

function($scope, $interval) {
    $scope.clock = new Date();
    var updateClock = function() {
        $scope.clock = new Date();
    };
    $interval(updateClock, 1000);
}

回答by SDekov

If you use the JS setInterval()then you will need $scope.$apply() to your method.

如果您使用 JS setInterval()那么您将需要 $scope.$apply() 到您的方法。

var updateClock = function() {
        $scope.clock = new Date();
        $scope.$apply();
    };

The better solution is to use $interval(angular)

更好的解决方案是使用$interval(angular)

$interval(updateClock, 1000);