Ways to display a specific section on an HTML page using AngularJS

Main page content

<div class="row">
    <div class="col-md-3">
        link 1
        link 2
        link 3
        .
        .
        .
    </div>
</div>

<div class="col-md-9">
    <div ng-view></div>
</div>

Clicking a link on the main page will load the child page in ng-view.

<table class='table table-bordered'>
    <tr>
        <td>
            This is the screen view.
            When a user clicks a link on the parent page, specific content is loaded here.
        </td>
    </tr>
</table>    


<button type="button" class="btn btn-success btn-md" ng-click="myprint()" >
    <span class="glyphicon glyphicon-print"></span> Print
</button>


<div id ="printsection">
    <table style="width:80mm;">
        <tr style="text-align: center;">
            <td>This is the print view contents. 
                These contents will be sent to the printer when printing.
            </td>
        </tr>
    </table>
</div>

The child page consists of two sections - screen view and print section.

Upon clicking the print button, the content from the print section will be sent to the printer.

CSS rules defined for media print:

print.css

body {
    background-color: white;
    color: black;
    font-family: Times,"Times New Roman",Garamond, serif;
}
body * {
    visibility: hidden;
}
#printsection * {
    visibility: visible;
}
#printsection {
    position: absolute;
    left: 0;
    top: 0;
}

The issue is that upon clicking the print button, all contents, including the print section, are being hidden.

Please note that an 80mm width POS printer is being used, hence the width set to 80mm in the print section.

Answer №1

One way to easily replace the content of a page and initiate printing is by using a simple function.

<button onclick="printElement('my-section')">Print</button>

function printElement(id) {
    var printHtml = document.getElementById(id).outerHTML;
    var currentPage = document.body.innerHTML;
    var elementPage = '<html><head><title></title></head><body>' + printHtml + '</body>';
    
    // Temporarily change the body content
    document.body.innerHTML = elementPage;
    
    // Print the modified content
    window.print();
    
    // Revert back to the original content
    document.body.innerHTML = currentPage;
}

When clicking the print button, ensure that you are also changing the visibility property of "printsection" to visible.

Below are some CSS rules for managing visibility:

display:none, display:block.

Answer №2

The visibility of the printSection and its parent elements was not set to visible. To rectify this, ensure that you apply the following CSS:

#printSection{
    visibility: visible;
}

Remember to also check and make all parent elements visible if they were hidden using body *{ ... }

Answer №3

If you want to customize the printing style of your webpage, consider using CSS media rules specifically for printing purposes: CSS media rules - @media print. Here is an example:

<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <style>

        @media all {
            /* Define styles applicable to all devices */
        }

        @media screen {
            /* Styles specific to screen display */
        }

        @media only print {
            /* Styles intended for printed material or print preview mode */
            main {
                display: none;
            }
        }
    </style>
</head>
<body>
    <main>
        <button onclick="window.print()">Print</button>
        <h1>hello</h1>
        <p>Some paragraph</p>
    </main>

    <div id="print-section">
        <h2>subtitle</h2>
        <table border="1" width="50%">
            <tbody>
            <tr>
                <td>A</td>
                <td>B</td>
            </tr>
            <tr>
                <td>C</td>
                <td>D</td>
            </tr>
            </tbody>
        </table>
    </div>
</body>
</html>

When a user initiates printing using CTRL + P or the print button with window.print(), only the content outside of the main tag will be included in the printout, following this best practice approach.

According to the documentation:
Syntax:

@media <media-query> {
  /* Define media-specific styles */
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript basic calculator app failed to generate an error as anticipated

For my homework assignment, I am developing a basic calculator application using JavaScript. My main task is to ensure that the input numbers are limited to only two and that they are valid numbers; otherwise, an error should be thrown. Initially, concern ...

Resolving the issue of data transmission within Yii2's framework: Page-to-page data

I'm currently using Yii2-advanced-app and I have encountered an issue. I want to pass the selected value from a dropdown menu to a PHP code that displays a list with checkboxes on the same page. Here is an image for reference on what I am trying to ac ...

Is there a way for me to retrieve a variable from outside a function?

I'm trying to access a variable outside of the function in Next.js. I want to retrieve the 'name' from the data object after making an API call. let getDetail = async () => { let body = { code: '12', provider: & ...

What is the method for enlarging the width of the nvd3 chart timespan?

Click here In the Plnkr linked above, I have included the latest versions of d3 and nvd3 libraries. Upon initial viewing of the chart, you may notice that all the timespan ticks such as 09:00, 08:30, 08:00, etc., are overlapping on the left xAxis. The ti ...

Having trouble with a beginner problem that's hindering the functionality of my code

I have been struggling with a particular piece of code and it is driving me crazy as I am unable to locate the source of my error: $.post($form.attr('action'), $form.serialize(), function (result) { console.log(result); if (result.succes ...

Failure to trigger bind action in connector.php for elfinder, a Javascript file manager plugin

function log() { $data = array( 'folder_id' => 1, 'user_id' => 1 ); $this->Folder_model->share($data); } function access($attr, $path, $data, $volume) { return strpos(basename($path), '. ...

When converting to a React Functional Component using Typescript, an error occurred: The property 'forceUpdateHandler' could not be found on the type 'MutableRefObject<Spinner | null>'

Looking to convert the App component in this CodePen into a Functional component using Typescript. Encountering an error when attempting to run it: ERROR in src/App.tsx:13:14 TS2339: Property 'forceUpdateHandler' does not exist on type 'Mu ...

Creating an associative array in javascript: A step-by-step guide

I require an array to be structured in the following manner: {"3": {"label":"All i want for christmas", "song":"Alliw_1405399165.mp3", "name":"All i want for christmas"}, "4": {"label":"Call your girlfriend robyn clip", "song":"Gang ...

IE8 does not support Jquery ajax() for cross domain requests to remote servers

My current script includes an ajax request to a remote server that provides a plain text response. This setup functions properly in all browsers with the exception of IE8, which is not surprising. The script snippet looks like this: $.ajax({ url: &apos ...

Is it possible to pass multiple API props to a NextJs Page at once?

I am currently facing a challenge in rendering a page that requires data from two different API fetches. The URL in the address bar appears as: http://localhost:3000/startpage?id=1 Below is the code snippet for the first API fetch: import { useRouter } f ...

Do you need to define a schema before querying data with Mongoose?

Is it necessary to adhere to a model with a schema before running any query? And how can one query a database collection without the schema, when referred by the collection name? This scenario is demonstrated in an example query from the Mongoose document ...

Click to Rotate the Shape

I am attempting to apply a rotation effect on a shape when clicked using jQuery and CSS. My goal is to select the element with the id of x and toggle the class rotate on and off. The rotate class utilizes the CSS transform property to achieve the desired r ...

Internet Explorer displaying incorrect shadow effects (paper curl) with CSS

I am attempting to achieve a page curl effect similar to this one: https://i.stack.imgur.com/grS7p.png I have followed the example provided here: http://codepen.io/anon/pen/fpjoa When I create new PHP and CSS files and copy-paste the code from the afore ...

Executing a controller function in AngularJS from an event

I am facing an issue with my AngularJS code. I have defined a function within my controller, and I am trying to call it inside an event listener, but I keep getting an 'undefined' error. Here is how the controller code looks like: inputApp.cont ...

Why does a string expression not function properly with the ng-bind directive, but a number expression does?

Take a look at these AngularJS examples: Example 1: <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> <div ng-app="" ng-init="quantit ...

Angular Single Page Application Development

Currently exploring the implementation of a single-page application in Angular.js Came across a helpful demo at http://scotch.io/demos/angular-single-page-routing which seems suitable for my needs. However, while browsing through http://scotch.io/demos ...

Exporting an HTML table to Excel with JavaScript runs into issues when it encounters the '#' character

Looking for a JavaScript solution to export HTML tables to Excel. I attempted a script that exports tables, but it stops when encountering special characters like '#'. Can someone assist me with this issue? Thank you in advance. <script src= ...

Top Choice for Customizable Location Bar Dragging

I'm currently working on an app that features a draggable location bar. This feature will allow users to navigate through chapters in a book and will be displayed at the bottom of the screen, similar to Kindle or other mobile reading applications. I ...

Combining the powers of Rails API with AngularJS and the Websocket-Rails gem

Currently, my server is utilizing the websocket-rails gem for managing websockets. I am encountering challenges integrating websocket-rails with a phonegap project that incorporates angular. This is because I require the ability to initialize the websocke ...

Obtaining values from alternating nodes in a SQL query

Can anyone help with extracting values of odd and even nodes in SQL from this XML example? declare @htmlXML xml = N'<div class="screen_specs_container "><div class="left_specs_container">Compatibility:</div><div class="right_spe ...