window.setInterval not working on angularjs

前端 未结 2 1450
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 09:31

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

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


        
相关标签:
2条回答
  • 2020-12-21 09:58

    Use the angular $interval service.

    function($scope, $interval) {
        $scope.clock = new Date();
        var updateClock = function() {
            $scope.clock = new Date();
        };
        $interval(updateClock, 1000);
    }
    
    0 讨论(0)
  • If you use the JS setInterval() then you will need $scope.$apply() to your method.

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

    The better solution is to use $interval (angular)

    $interval(updateClock, 1000);
    
    0 讨论(0)
提交回复
热议问题