AngularJS:暂停隐藏DOM元素的$ digest和watchers

Yog*_*gaj 5 optimization angularjs

我们正在构建一个单页面应用程序,它将多个页面作为选项卡加载.只有一个选项卡的内容在任何给定时间都可见(很像浏览器),因此我们希望暂时暂停$digest和观察者在隐藏选项卡的DOM节点上执行,直到用户切换到该选项卡.

有没有办法实现这一点,以便继续为背景选项卡更新模型,但视图会根据条件进行更新.

以下代码说明了该问题:

<div ng-repeat="tab in tabs" ng-show="tab.id == current_tab.id">
    <!-- tab content with bindings -->
</div>
Run Code Online (Sandbox Code Playgroud)

目标是优化.

我已经知道了Scalyr指令,但我想要一个更具体的解决方案,而不需要Scalyr中包含的额外功能.

Yog*_*gaj 7

经过一些试验和错误后,我发现了以下指令,$$watchers如果属性上的表达式求值true,则暂停所有子节点,在false其上恢复任何备份$$watchers

app.directive('pauseChildrenWatchersIf', function(){
    return {
        link: function (scope, element, attrs) {

            scope.$watch(attrs.pauseChildrenWatchersIf, function (newVal) {
                if (newVal === undefined) {
                    return;
                }
                if (newVal) {
                    toggleChildrenWatchers(element, true)
                } else {
                    toggleChildrenWatchers(element, false)
                }
            });
            function toggleChildrenWatchers(element, pause) {
                angular.forEach(element.children(), function (childElement) {
                    toggleAllWatchers(angular.element(childElement), pause);
                });
            }

            function toggleAllWatchers(element, pause) {
                var data = element.data();
                if (data.hasOwnProperty('$scope') && data.$scope.hasOwnProperty('$$watchers') && data.$scope.$$watchers) {
                    if (pause) {
                        data._bk_$$watchers = [];
                        $.each(data.$scope.$$watchers, function (i, watcher) {
                            data._bk_$$watchers.push($.extend(true, {}, watcher))
                        });

                        data.$scope.$$watchers = [];
                    } else {
                        if (data.hasOwnProperty('_bk_$$watchers')) {
                            $.each(data._bk_$$watchers, function (i, watcher) {
                                data.$scope.$$watchers.push($.extend(true, {}, watcher))
                            });
                        }
                    }

                }
                toggleChildrenWatchers(element, pause);
            }
        }
    }
});
Run Code Online (Sandbox Code Playgroud)