I have been trying to update a clock time displayed in an h1
element. My approach was to update the time by calling a function using setInterval, but I faced difficulties in making the call. Eventually, I discovered that using the apply
method provided a solution.
However, I am curious about the reasoning behind this issue. Can someone explain why I couldn't make the call and why it was necessary to use the apply method?
Here is my code snippet:
angular.module('Book', [])
.controller('MyController', function ($scope) {
var updateClock = function() {
$scope.clock = new Date();
};
setInterval(function() {
updateClock(); //not working when called from here...?
//$scope.$apply(updateClock); //it works!
}, 1000);
updateClock(); //works the first time.
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="Book">
<div ng-controller='MyController'>
<input ng-model="name" type="text" placeholder="Your name">
<h1>Hello {{ clock }}</h1>
</div>
</div>