ArticleZip > Print A Div Using Javascript In Angularjs Single Page Application

Print A Div Using Javascript In Angularjs Single Page Application

Coding in AngularJS is a great way to make your web applications more dynamic and interactive. And one common task you may encounter is printing a specific section of your page, like a div element. In this article, we'll walk you through how to achieve this using JavaScript within an AngularJS single-page application (SPA).

To begin, we first need to create a function that will handle the printing logic. Let's call it `printDiv`. This function will utilize JavaScript's `window.print()` method, which triggers the browser's built-in print functionality. Here's how you can implement the `printDiv` function:

Javascript

$scope.printDiv = function(divName) {
  var printContents = document.getElementById(divName).innerHTML;
  var originalContents = document.body.innerHTML;

  document.body.innerHTML = printContents;

  window.print();

  document.body.innerHTML = originalContents;
}

In the code snippet above, we pass the name of the div we want to print as a parameter to the `printDiv` function. The function then gets the inner HTML content of the specified div and stores it in the `printContents` variable. We also backup the original contents of the document body in `originalContents`.

Next, we replace the content of the document body with the HTML content of the target div so that when we call `window.print()`, only the content of the div will be sent to the printer. After printing, we restore the original contents of the document body.

Now, let's incorporate this function into an AngularJS single-page application. Assuming you have a div element in your HTML template with the id `myPrintableDiv`, you can call the `printDiv` function as follows:

Html

<div id="myPrintableDiv">
  <!-- Content to be printed -->
</div>

<button>Print</button>

In the snippet above, we have a button that, when clicked, will trigger the `printDiv` function passing 'myPrintableDiv' as the argument, which signifies the id of the div we want to print. Make sure to replace `'myPrintableDiv'` with the actual id of your target div.

By following these steps, you can easily enable printing of a specific div within your AngularJS SPA. This feature can be particularly useful for generating printable reports, invoices, or any other content that you want to provide a print-friendly version for users.

In conclusion, printing a div using JavaScript in an AngularJS single-page application is a manageable task that enhances the user experience of your web application. Implementing the `printDiv` function as demonstrated above will empower you to control what content gets printed from your SPA.

×