Quantcast
Channel: AngularJS : Prevent error $digest already in progress when calling $scope.$apply() - Stack Overflow
Viewing all articles
Browse latest Browse all 29

Answer by Sergey Sahakyan for AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

$
0
0
        let $timeoutPromise = null;        $timeout.cancel($timeoutPromise);        $timeoutPromise = $timeout(() => {            $scope.$digest();        }, 0, false);

Here is good solution to avoid this error and avoid $apply

you can combine this with debounce(0) if calling based on external event. Above is the 'debounce' we are using, and full example of code

.factory('debounce', ['$timeout',    function ($timeout) {        return function (func, wait, apply) {            // apply default is true for $timeout            if (apply !== false) {                apply = true;            }            var promise;            return function () {                var cntx = this,                    args = arguments;                $timeout.cancel(promise);                promise = $timeout(function () {                    return func.apply(cntx, args);                }, wait, apply);                return promise;            };        };    }])

and the code itself to listen some event and call $digest only on $scope you need

        let $timeoutPromise = null;        let $update = debounce(function () {            $timeout.cancel($timeoutPromise);            $timeoutPromise = $timeout(() => {                $scope.$digest();            }, 0, false);        }, 0, false);        let $unwatchModelChanges = $scope.$root.$on('updatePropertiesInspector', function () {            $update();        });        $scope.$on('$destroy', () => {            $timeout.cancel($update);            $timeout.cancel($timeoutPromise);            $unwatchModelChanges();        });

Viewing all articles
Browse latest Browse all 29

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>