window.setInterval在angularjs上不起作用 [英] window.setInterval not working on angularjs

查看:145
本文介绍了window.setInterval在angularjs上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this small piece of code that uses setInterval method:

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

和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>

但是,MyController中的setInterval不会更新时间. 这里哪里可能错了?

However, setInterval in MyController does not update time. Where possibly is wrong here ?

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

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

为什么会这样,而在不使用@ scope.$ apply的情况下出了什么问题?

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

推荐答案

使用有角 $ interval 服务.

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

这篇关于window.setInterval在angularjs上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆