1

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...

dopatraman
  • 13,416
  • 29
  • 90
  • 154

2 Answers2

6

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: How does data binding work 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/

Community
  • 1
  • 1
pkozlowski.opensource
  • 117,202
  • 60
  • 326
  • 286
  • I suppose so, but doesnt this defeat the point of the databinding feature? -_- – dopatraman 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
  • How is that supposed to work? When I try something like this it only executes the timedout function once. I don't use the time but a textual representation. I presume watch doesn't check after it was the same twice. – w00t Jun 29 '13 at 13:13
0
var updateTime = function () {
    $scope.currentTime = new Date();
    $timeout(updateTime, 1000);
};
updateTime();