如何暂停和恢复范围。$$观察者?

时间:2015-05-18 14:48:18

标签: angularjs angularjs-directive

我在angularjs 1.4中创建了复杂的表单。我需要使用模态对话框,但主表单中的观察者对性能影响很大。 我使用next方法禁用观察者:

.directive('suspendable', ['$timeout', function ($timeout) {
return {
    link: function (scope) {
        // Heads up: this might break is suspend/resume called out of order
        // or if watchers are added while suspended
        var watchers;
        var depth = 0;
        scope.$on('suspend', function (event, args) {
            if(watchers){
                return;
            }
            depth = args.depth;
            watchers = scope.$$watchers;
            scope.$$watchers = [];              
            console.log(depth + ' suspend ' + (watchers?watchers.length:0));
        });

        scope.$on('resume', function (event, args) {
            if (watchers && (depth == args.depth)) {
                scope.$$watchers = watchers;
                scope.$$watchersCount = watchers.length;
                watchers = void 0;                  
                console.log(depth + ' resume ' + (watchers.length));
            }
        });
    }
};}])

我将suspendable指令添加到主表单中的所有指令中,并在show modal对话框之前调用广播事件suspend,并在对话框关闭后调用广播事件resume。但是在恢复之后我还没有获得观察者的功能。

2 个答案:

答案 0 :(得分:0)

我更改了resume

scope.$on('resume', function (event, args) {
            if (watchers && (depth == args.depth)) {
                if (!scope.$$watchers ) {
                    scope.$$watchers = watchers;
                } else {
                    scope.$$watchers = scope.$$watchers.concat(watchers);
                }
                console.log(depth + ' resume ' + (watchers.length));
                watchers = void 0;
            }
        });

它帮助了我!

答案 1 :(得分:0)

AngularJS 1.7具有一项新功能-能够暂停和恢复范围观察器- https://github.com/angular/angular.js/commit/41d5c90f170cc054b0f8f88220c22ef1ef6cc0a6

scope.$suspend()的调用将阻止在摘要期间执行此作用域子树的观察者。

呼叫scope.$resume()将恢复观察者的执行。

相关问题