Please explain to me why we have $scope.variable twice first inside and outside the nested function?

StackOverflow https://stackoverflow.com/questions/22182632

  •  05-06-2023
  •  | 
  •  

Question

function MyController($scope){ 
$scope.clock = new Date(); <---here
var updateClock = function() {
$scope.clock = new Date(); }; <---and here
setInterval(function() { $scope.$apply(updateClock);}, 1000);
updateClock();

}; I thought I knew javascript but I cannot understand what author did it here. Please help me to understand this function! Thanks in advance!

Was it helpful?

Solution

The first is initializing $scope.clock when the controller is created. That's the only time the first $scope.clock = new Date(); will be run. The second time, the function is updating the clock property on the $scope object, to set it with a new date.

This block would cause $scope.clock to be undefined until the timeout executes 10 seconds later:

function MyController($scope){ 
    var updateClock = function() 
    {
        $scope.clock = new Date(); 
    };
    setTimeout(function() { $scope.$apply(updateClock);}, 10000);
}

This block, $scope.clock is initialized when the controller is created:

function MyController($scope){ 
    $scope.clock = new Date();
    var updateClock = function() 
    {
         $scope.clock = new Date(); 
    };
    setTimeout(function() { $scope.$apply(updateClock);}, 10000);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top