kslstn
kslstn

Reputation: 1656

How to update elements that are bound to functions with Angular?

What is the correct way to do have elements update regularly, without explicitly doing that for each variable in an $interval callback?

This would be useful in the following situation: an element's content is bound to a function, like this:

<p ng-bind="timeLeft()"></p>

The timeleft() function returns a value depending on the current time. It needs to be refreshed every 20 ms.

Edit: usually ngBind updates just fine, but I guess because the outcome of timeLeft() only depends on time passing, in this case it doesn't. Without the code below, the view is not updated after loading the DOM, at least not without updating other values.

I've tried the following, which works:

$scope.updateView = function(){
    if(!$scope.$$phase) { // To prevent this: "Error: [$rootScope:inprog] $digest already in progress"
        $scope.apply();
    }
}
$interval( function(){
    $scope.updateView();
}, 50);

I noticed just using $interval may already suffice, in my setup this works too:

$scope.updateView = function(){
}
$interval( function(){
    $scope.updateView();
}, 20);

Would it be reliable to use that last solution?

Upvotes: 0

Views: 300

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

Yes, you should be reliable with second solution. Angular does not run the digest cycle when event occurred from outside angular context, at that you need to tell AngularJs to run apply cycle to update all bindings. When you are using $interval angular will run digest cycle after an execution of callback function, there is no need of running digest cycle which you have done in your 1st solution.

You need to look at $interval service

$interval($scope.updateView, 
  20, //delay
  10, //this option will run it 10 times, if not specified then infinite times 
  true, //do you want to run digest cycle after callback execution, defaulted to true
  {} //any extra params
);

Upvotes: 1

Related Questions