如何在页面加载后自动触发角度指令

时间:2014-09-11 20:53:35

标签: javascript jquery angularjs

print="id"属性位于<a></a>时,我会调用一个print指令。该按钮位于用户不可见的模态中。因此,只要模态加载,我就需要指令关闭。 它会在模态底部的简单脚本中吗?

<a href="#" print="jobSetupPrintPdf"><button>Print</button></a>

<script type="text/javascript">
    $(window).load(function () {
       ????????
    });
</script>

这是我在模态加载

后尝试触发的指令
app.directive('print', ['$compile', function ($compile) {
    return {
        restrict: 'AEC',
        link: function (scope, el, attrs) {
            if (attrs.nopopup) {
                el.bind('click', function () {
                    window.print();
                });
            } else {
                el.bind('click', function () {
                    var html = document.getElementById(attrs.print);
                    var links = document.getElementsByTagName('link');
                    var stylesheets = "";
                    for (var i = 0; i < links.length; i++) {
                        stylesheets = stylesheets + links[i].outerHTML;
                    }
                    var printarea = window.open('', '', '');
                    printarea.document.write('<html><head><title></title>');
                    printarea.document.write(stylesheets);
                    printarea.document.write('</head><body>');
                    printarea.document.write(html.innerHTML);
                    printarea.document.write('</body></html>');
                    setTimeout(function () {
                        printarea.print();
                        printarea.close();
                    }, 100);
                });
            }
        }
    };
}]);    

更新

<a href="#" print="jobSetupPrintPdf" id="testing">Print</a>
 <script type="text/javascript">
  $('#testing').click()
 </script>

错误消息

Error: [$rootScope:inprog] $digest already in progress

我正在阅读我需要添加$ timeout或延迟?我无法弄清楚如何在这里应用它

1 个答案:

答案 0 :(得分:0)

似乎你真正需要做的就是将打印包装成一个函数。如果您仍然需要使用按钮,请立即调用相应的函数并将其用作点击处理程序。

app.directive('print', ['$compile', function ($compile) {
    return {
        restrict: 'AEC',
        link: function (scope, el, attrs) {

            function simplePrint(){
                window.print();
            }

            function fancyPrint(){                    
                /* code for other window */
            }
            if (attrs.nopopup) {
                simplePrint();
                el.bind('click',simplePrint);
            } else {
                fancyPrint();
                el.bind('click', fancyPrint);
            }
        }
    };
}]); 

请记住,如果您在页面中创建了角色html,则需要花一些时间在打印前构建每个内容