My coding snippet involves the use of the setInterval method:
function MyController($scope) {
$scope.clock = new Date();
var updateClock = function() {
$scope.clock = new Date();
};
setInterval(updateClock, 1000);
};
The HTML associated with this is 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, there seems to be an issue with the update functionality in setInterval
inside MyController
. What could possibly be wrong here?
As per a reference source, it should be done like this:
function MyController($scope) {
$scope.clock = new Date();
var updateClock = function() {
$scope.clock = new Date();
};
setInterval(function() {
$scope.$apply(updateClock);
}, 1000);
updateClock();
};
Why does using $scope.$apply
make a difference and what might go awry if it's not included?