4

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

and html as follows:

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

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

1
  • Will you please give a js fiddle link for this. Commented Jul 3, 2015 at 13:15

2 Answers 2

12

Use the angular $interval service.

function($scope, $interval) {
    $scope.clock = new Date();
    var updateClock = function() {
        $scope.clock = new Date();
    };
    $interval(updateClock, 1000);
}
Sign up to request clarification or add additional context in comments.

4 Comments

I understand I could use that and is the preferable way to do it, but could you please throw some light why did it now work with setInterval ? Infact, if instead of passing updateClock directly to setInterval, if I had done $scope.@apply(updateclock), it works. I am trying to know the reason after this.
Inside of a traditional setInterval function, Angular does not know about your updates, and thus, you must $apply() it yourself. For example, you could leave it how it was and in your updateClock method call $apply after you change the value to tell Angular you've updated. Instead, using the built in $interval (or $timeout) functions, this work is done for you. Additionally, these return a promise, so you can actually do work on them via ` .then()` if you'd like.
Why is updateClock without parenthesis, like this: updateClock()?
@munchschair that's the syntax used for $interval
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.