$编译HTML模板并仅在$ compile完成后执行打印操作

时间:2014-11-07 12:57:09

标签: angularjs angularjs-directive

在指令链接功能中,我想向文档的DIV添加一个已编译的ad-hoc模板,然后打印该窗口。我尝试以下代码和打印机预览出现,但预览中的数据仍然没有编译。

// create a div
printSection = document.createElement('div');
printSection.id = 'printSection';
document.body.appendChild(printSection);

// Trying to add some template to div
scope.someVar = "This is print header";
var htmlTemplate = "<h1>{{someVar}}</h1>"; 
var ps = angular.element(printSection);
ps.append(htmlTemplate);
$compile(ps.contents())(scope);

// What I must do to turn information inside printSection into compiled result 
// (I need later to have a table rendered using ng-repeat?)

window.print();
// ... currently shows page with "{{someVar}}", not "This is print header"

是不是因为$ compile不同步?如何在完成编译后触发window.print()?

1 个答案:

答案 0 :(得分:1)

您只需要完成当前的消化过程即可打印

如此改变

window.print();

_.defer(function() {
    window.print();
});

或$ timeout,或任何延迟处理程序。

会做到这一点。

另一种方式(可能是'正确的'方法)是在退出当前的$ apply阶段之前强制执行新编译的内容的观察者:

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