Skip to content

Instantly share code, notes, and snippets.

@agray
Created February 27, 2015 03:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save agray/6f8e0325f66be2be808e to your computer and use it in GitHub Desktop.
Save agray/6f8e0325f66be2be808e to your computer and use it in GitHub Desktop.
A working angularJS print directive
(function (angular) {
"use strict";
function printDirective() {
var printSection = document.getElementById("printSection");
function printElement(elem) {
// clones the element you want to print
var domClone = elem.cloneNode(true);
if (!printSection) {
printSection = document.createElement("div");
printSection.id = "printSection";
document.body.appendChild(printSection);
} else {
printSection.innerHTML = "";
}
printSection.appendChild(domClone);
}
function link(scope, element, attrs) {
element.on("click", function () {
var elemToPrint = document.getElementById(attrs.printElementId);
if (elemToPrint) {
printElement(elemToPrint);
window.print();
}
});
}
return {
link: link,
restrict: "A"
};
}
angular.module("app.directives").directive("ngPrint", [printDirective]);
}(window.angular));
@agray
Copy link
Author

agray commented Feb 27, 2015

This will work on any div it is attached to as you would expect.

The version here, just doesn't target divs correctly.

This directive can be used in an MVC Razor file like so:

<a class="btn btn-success" ng-print print-element-id="@Model.SomeId" value="Print"><span class="glyphicon glyphicon-print"></span><span class="hidden-sm hidden-xs">Print</span></a>

<div id="@Model.SomeId">
    This will be printed....
</div>

@nirmalgoswami
Copy link

Thanks for sharing this but i have issue i am getting extra one blank page

is there any solution for that ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment