Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This is the Angular JS function on my page:

function DateCtrl($scope) {

        $scope.returndate = function () {

            return Date.now();
        }

    }

The markup is as follows:

<html ng-app>
<body>    
<div id = "date" class = "stats" ng-controller = "DateCtrl">
            <span>Date:</span><div id = "noedate">{{returndate()}}</div>
    </div>
</body>
</html>

You would expect the date returned in #nowdate to change every second thanks to the data-binding, but it does not. Does anyone know what is wrong here?

I would provide a fiddle but jsfiddle does not support angular yet...

share|improve this question
AngularJS works perfectly with jsFiddle, check this: pkozlowskios.wordpress.com/2012/08/12/… – pkozlowski.opensource Aug 14 '12 at 15:07

2 Answers

up vote 4 down vote accepted

The data won't get updated automatically since AngularJS doesn't constantly pool for changes but only refreshes templates in response to certain events. You can check this post: Databinding in angularjs for more info on inner workings of angular.

If you would like to refresh certain value after a given period of time use the $timeout service (http://docs.angularjs.org/api/ng.$timeout).

Actually it is very easy to do a clock in AngularJS using combination of $watch and $timeout:

$scope.time = new Date();  
$scope.$watch('time', function(){
    $timeout(function(){
        $scope.time = new Date();
    },1000);
});

Here is the complete jsFillde: http://jsfiddle.net/pkozlowski_opensource/f5ApP/1/

share|improve this answer
I suppose so, but doesnt this defeat the point of the databinding feature? -_- – codeninja Aug 14 '12 at 16:00
1  
@codeninja, to have data-binding to update a template automatically you need to decide when to update. There are many options: refresh periodicity, pool for changes or refresh on certain events. AngularJS have chosen to update DOM (after dirty-checking) in response to certain events (user action, xhr calls, location changes etc.). This is just a design choice you need to be aware of when working with AngularJS. – pkozlowski.opensource Aug 14 '12 at 16:13
var updateTime = function () {
    $scope.currentTime = new Date();
    $timeout(updateTime, 1000);
};
updateTime();
share|improve this answer
It would be useful if you could add a brief explanation of your code. – Ren Apr 24 at 13:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.