强制角度考虑范围属性"脏"

时间:2014-11-06 14:02:32

标签: angularjs

有没有办法强制角度重新渲染绑定到属性的东西,即使属性没有改变值? e.g:

$scope.size = 1;

<div some-prop="size"></div>

$scope.$needsRender('size') // psuedocode
$scope.$apply(); // re-renders the <div>

不幸的是,出于性能原因,我无法完全按角度管理属性,这就是我需要“重置”的原因。

1 个答案:

答案 0 :(得分:2)

在角度之外操纵的角度DOM是丑陋的。说实话,不止于此。这样做的人可能应该死。慢。痛苦。

但无论如何是的,这是可能的。

简短回答:你可以这样做,强制执行范围的观察者。

module.factory("scopeUtils", function($parse) {

    var scopeUtils = {

        /**
         * Apply watchers of given scope even if a digest progress is already in process on another level.
         * This will only do a one-time cycle of watchers, without cascade digest.
         *
         * Please note that this is (almost) a hack, behaviour may be hazardous so please use with caution.
         *
         * @param {Scope} scope : scope to apply watchers from.
         */
        applyWatchers : function(scope) {
            scopeUtils.traverseScopeTree(scope, function(scope) {
                var watchers = scope.$$watchers;
                if(!watchers) {
                    return;
                }
                var watcher;
                for(var i=0; i<watchers.length; i++) {
                    watcher = watchers[i];
                    var value = watcher.get(scope);
                    watcher.fn(value, value, scope);
                }
            });
        },

        traverseScopeTree : function(parentScope, traverseFn) {
            var next,
                current = parentScope,
                target = parentScope;
            do {
                traverseFn(current);

                if (!(next = (current.$$childHead ||
                    (current !== target && current.$$nextSibling)))) {
                    while(current !== target && !(next = current.$$nextSibling)) {
                        current = current.$parent;
                    }
                }
            } while((current = next));
        }

    };

    return scopeUtils;
});

就像这样使用它:

scopeUtils.applyWatchers(myScope);