WindowsetInterval not working on angularjs
I have this little piece of code that uses the setInterval method :
function MyController($scope) {
$scope.clock = new Date();
var updateClock = function() {
$scope.clock = new Date();
};
setInterval(updateClock, 1000);
};
and html like this:
<!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
, the time MyController
does not update. Where, perhaps, is wrong here?
This works according to the book:
function MyController($scope) {
$scope.clock = new Date();
var updateClock = function() {
$scope.clock = new Date();
};
setInterval(function() {
$scope.$apply(updateClock);
}, 1000);
updateClock();
};
Why is it and what is wrong without using @scope. $ apply?
+3
source to share
2 answers
Use the angular $ interval service .
function($scope, $interval) {
$scope.clock = new Date();
var updateClock = function() {
$scope.clock = new Date();
};
$interval(updateClock, 1000);
}
+9
source to share