Is any event "on $scope digest finished" or "on view refreshed" in Angular.js?

3.6k Views Asked by At

I'm doing an AJAX request for data that is used in the view for generation of a list. I need to know when the $scope is updated and when the view is rendered after a successful response received, so that I can set dynamically some initial values and some event handlers for the list.

I'm currently using the following code which is not doing the trick:

responsePromise.success(function (data, status, headers, config) {
    var slideInfos = data;
    $scope.slideInfos = slideInfos;
    setInitialSliderValues();
});

At the time I call setInitialSliderValues() the view is still not refreshed.

When I try using the following I get an error "$digest already in progress":

responsePromise.success(function (data, status, headers, config) {
    var slideInfos = data;
    $scope.$apply(function () {
        $scope.slideInfos = slideInfos ;
        setInitialSliderValues();
    }
});

How can I be absolutely sure that changes to the data have taken effect on the page without the use of a timer that checks for the changes I expect.

2

There are 2 best solutions below

3
On BEST ANSWER

Use $timeout() that will get run in the next digest cycle. Don't forget to add $timeout dependency on controller.

$timeout(function () {
    $scope.slideInfos = slideInfos ;
    setInitialSliderValues();
});
5
On

You can try using $evalAsync:

responsePromise.success(function (data, status, headers, config) {
    $scope.slideInfos = data;
    $scope.$evalAsync(function () {        
        setInitialSliderValues();
    }
});

Unlike $timeout, it will try to fire within the same digest cycle if possible, if not it will be resolved in the next digest-cycle.