AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

前端 未结 28 2759
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 22:31

I\'m finding that I need to update my page to my scope manually more and more since building an application in angular.

The only way I know of to do this is to call

28条回答
  •  别跟我提以往
    2020-11-21 23:19

            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();
            });
    

提交回复
热议问题