The print function is being triggered before the partial view

My goal is to open a partial view in a new window and call the print function, but I'm facing an issue where the partial view renders after the print function, resulting in a blank page. I attempted using the $timeout function, but encountered the same problem. Currently, my workaround is as follows:

$scope.print = function() {
    setTimeout(function() {
        print()
    }, 1000);
}

Here is the HTML of the page I am trying to open:

<div id="printWrapper" style="background-color:white;" ng-controller="accountContentController" ng-init="print()">
    <table border="0" cellpadding="0" cellspacing="0" width="100%">
        <!-- HEADER -->
        <tr>
            <td>

                <img id="imgLogo" src="@Model.TicketPayOut.Logo" />


            </td>
        </tr>
        <!--HEADER-->
        <tr>
            <td>
                <label id="lblTerminalId" class="left-position padding-top-3 padding-left-3 text-style">@Translator.Translate("TERMINAL")</label>
                <span class="left-position padding-top-3 text-style">:</span>
                <label id="lblTerminalIdValue" class="left-position padding-top-3 padding-left-3 text-style"></label>

                <div style="clear:both"></div>

                <label id="lblTerminalName" class="left-position padding-left-3 text-style">@Translator.Translate("BET_OFFICE")</label>
                <span class="left-post text-style">:</span>
                <label id="lblTerminalNameValue" class="left-position padding-left-3 text-style"></label>

                <label id="lblTerminalCityAddress" class="left-position padding-left-3 text-style" style="clear:both;"></label>

                <label id="lblCompanyInfo" class="center-position text-style" style="clear:both;"></label>
                <label id="lblCompanyAddress" class="center-position text-style" style="clear:both;"></label>
                <label id="lblCompanyId" class="center-position text-style" style="clear:both;"></label>

            </td>
        </tr>

        <tr>
            <td class="border-top border-bottom">
                <div style="padding:10px 0;">
                    <label id="lblStornoMessage" class="center-position text-style">@Translator.Translate("PAYOUT_CONFIRMATION")</label>
                </div>
            </td>
        </tr>
        <tr>
            <td class="border-bottom">

                <div style="height:25px;padding:10px 3px 0 3px;">
                    <label id="lblPayoutTicket" class="left-position text-style">@Translator.Translate("PAYOUT_TICKET")</label>
                    <label id="lblPinValue" class="right-position text-style">{{payoutTime | date: dateFormat }}</label>

                </div>
            </td>
        </tr>
        <tr>

            <td>
                <div style="padding:5px 3px;">

                    <label id="lblPinTicket" class="left-position text-style">@Translator.Translate("PIN")</label>
                    <label id="lblPinReturnValue" class="right-position text-style">{{ticketPin}}</label>
                </div>
            </td>
        </tr>
        <tr>
            <td>
                <div style="padding:5px 3px;">
                    <label id="lblPayinReturn" class="left-position text-style">@Translator.Translate("PAYOUT_AMOUNT")</label>
                    <label id="lblPayinReturnValue" class="right-position text-style">{{payoutAmount}}</label>
                </div>

            </td>
        </tr>


        <tr>
            <td class="border-bottom">
                <div style="padding:25px 3px 5px 3px;">
                    <label id="lblCreatedBy" class="left-post text-style">@Translator.Translate("CREATED_BY")</label>
                    <label id="lblCreatedByValue" class="right-position text-style">@User.Identity.Name</label>

                </div>
            </td>
        </tr>
    </table>
</div>

This button on the page includes the print option:

  <div class="mr-10">
                    <div class="pull-right padding-8 mt5 col-lg-2 col-md-2">
                        <input type="submit" value="@Translator.Translate("CANCEL")" class="btn btn-block secondary-button save-changes padding-8" ng-click="CancelPayOutTicket(ticketPin)" />
                    </div>
                    <div class="pull-right padding-8 mt5 col-lg-2 col-md-2">
                        <input type="submit" value="@Translator.Translate("PAYOUT")" class="btn btn-block save-changes padding-8" ng-class="{'secondary-button':TicketsPayout.BettingSlipResult.TicketHolder.PayoutEnabled==true,'disabled_button':TicketsPayout.BettingSlipResult.TicketHolder.PayoutEnabled==false}" ng-disabled="TicketsPayout.BettingSlipResult.TicketHolder.PayoutEnabled==false" ng-click="FinishTicketPayout(ticketPin);ConfirmTicketPayOut(ticketPin,'@username')"/>
                    </div>
                 </div>

I'm seeking a way to eliminate the use of the setTimeout function and directly call the print function in a new window while populating the partial view with data.

Edit: Angular controller code snippet:

$scope.CheckTicket = function (ticketPin) {


           if (ticketPin != null && ticketPin != "" && ticketPin != undefined) {
            var promise = accountDataProviderService.checkTicketPayout(ticketPin);

            $scope.checkPromise = promise;

            promise.then(
           function (response) {
               $scope.showTicketPayout = true;
               $scope.TicketsPayout = response;

           },
         function (err) {
             $scope.showTicketPayout = false;
             $scope.ticketNotFound = true;
             $timeout(function ()
             {
                 $scope.ticketNotFound = false;
             }, ticketNotFound * 1000);
         });

        }
... (continued)

Answer №1

Transform the data "package" into a promise within your controller:

angular.module("printModule").controller('printController', ['$scope', '$window', '$q', function ($scope, $window, $q) { 


$scope.ticketPin = localStorage.getItem("pin"); 
$scope.payoutTime = localStorage.getItem("payoutTime"); 
$scope.payoutAmount = localStorage.getItem("payoutAmount"); 

var defer = $q.defer(); 
defer.resolve($scope.ticketPin); 
defer.resolve($scope.payoutTime); 
defer.resolve($scope.payoutAmount); 

defer.promise.then(function () { 
    $window.print(); 
}) 
}]);

Wishing you a wonderful day :)

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

Tips for preventing useEffect from triggering a route?

Recently delving into reactjs, I stumbled upon a situation in the code where the route alerts messages twice. I'm seeking advice on how to prevent this issue, please disregard the redux code involved. Any suggestions? Index.js import React from &apos ...

Can you tell me how to add a variable to an array of objects in JavaScript?

I am currently engaged in a small project aimed at: Reading data from a CSV file (such as employee names and shifts) Displaying this data on FullCalendar. How can I incorporate the CSV result into this line of code: { id: 'a', title: 'Audi ...

Encountered a cross-domain error with node.js and jQuery: ERR_CONNECTION_REFUSED

Just beginning my journey with Node.js. I've set up a basic node/express application that serves a single webpage featuring a button. When clicked, this button triggers a jQuery ajax request to an Express route. The route callback then makes an http ...

Determine the byte size of the ImageData Object

Snippet: // Generate a blank canvas let canvas = document.createElement('canvas'); canvas.width = 100; canvas.height = 100; document.body.appendChild(canvas); // Access the drawing context let ctx = canvas.getContext('2d'); // Extrac ...

Encountering difficulties in applying a dynamic aria-label to the md-datepicker component

I am currently utilizing the md-datepicker feature in my project. You can check out how it works here: https://material.angularjs.org/latest/demo/datepicker However, I am facing an issue where I am unable to dynamically add a value to the aria-label attri ...

Are the sorting algorithms for BackboneJS and AngularJS considered stable sorting methods?

I'm considering incorporating BackboneJS and AngularJS into my app. However, I'm curious about the stability of sorting algorithms in these frameworks. Specifically, I would like to know if they maintain the order of previously sorted columns wit ...

No output is displayed in the absence of errors. The program is functioning correctly

app.js angular.module('app', ['ionic', 'ui.router']) .config(('$urlRouterProvider', '$stateProvider', function($urlRouterProvider,$stateProvider){ $urlRouterProvider.otherwise('/'); $sta ...

"Ensure that the data in the div is being updated accurately via AJAX in ASP.NET MVC

I'm currently using a div element to display data on page load through AJAX calls. $(document).ready(function () { email_update(); }); function email_update() { $.ajax({ url: '@Url.Action("EmailsList", "Questions")', ...

Showing fixed values inside directive view after successful injection

Looking for some answers about using constants in angularjs. Here are the constants defined in my app.js: ... angular .module('blocTime', ['firebase', 'ui.router']) .config(config) .constant(&apos ...

Angular - Collaborative HTML format function

In my project, I have a function that sets the CSS class of an element dynamically. This function is used in different components where dynamic CSS needs to be applied. However, every time I make a change to the function, I have to update it in each compo ...

Utilizing the Google Geocode API to handle a promise with a substantial array

My Objective To efficiently process a large array using the .map method and interact with the Google Geocoder API through promises to get location data. The goal is to utilize Promise.all to store results in a .json file upon completion of the operation. ...

The v-data-table is unable to fetch the user list information from the API using Axios

How can I solve the issue of displaying "No data available" in the user list data table on my userDirectory page? I have created a userDirectory page with a subheader and a data table from Vuetify, but it seems to have no data available. <template> ...

How to properly handle Angular routing errors and best practices?

Currently, I have been delving into learning Angular to integrate with my Ruby on Rails application. However, I have encountered some challenges specifically related to routing. Here is a snippet from my app.routing file: import { NgModule } from '@ ...

Can someone explain the significance of receiving a TypeError when trying to access properties of null (specifically 'useRef') in a React application?

I encountered an issue while working on a React project...the browser console displays the following error. What does this mean? And how can I resolve it? react.development.js:1545 Uncaught TypeError: Cannot read properties of null (reading 'useRef ...

Is there a way to prompt WebAPI to receive a complicated object as its argument for a DELETE HTTP request without relying on C# attributes?

Currently, my server is utilizing C#/WebAPI while the client side is using AngularJS. I am faced with a dilemma when it comes to formatting an HTTP DELETE request without specifying attributes in C#. Specifically, I am struggling with how to handle a meth ...

How about I visit the campgrounds/edit page for a change?

In this get route, the previous link it was redirected from is stored in the req.session object under returnTo. Once redirected, it goes to the /login and we are able to view the object in the console. router.get('/login', (req, res) => { ...

Issue with Angular UI Bootstrap accordion heading behavior when used in conjunction with a checkbox is causing

I have implemented a checkbox in the header of an accordion control using Bootstrap. However, I am facing an issue where the model only updates the first time the checkbox is clicked. Below is the HTML code for the accordion: <accordion ng-repeat="tim ...

Issues occurring with setting the variable using the Google latlng API

I've tried searching for solutions on various forums, including stackoverflow, but haven't been able to make it work. The issue lies in this code snippet where the variable 'pos' is not being set: var geocoder= new google.maps.Geocoder ...

What is the reason behind every single request being treated as an ajax request?

Recently, I embarked on a new application development journey using rails 4.0. However, I've encountered an unexpected situation where every request is being processed as an ajax request. For instance, consider this link: =link_to "View detail", pr ...

Using jQuery and Ajax to fade in content after all images and other assets have finished loading

I've encountered an issue with loading pages via ajax for users with custom URLs. For example, a profile is usually found at http://example.com/users/Dan, but if a user has a custom URL like http://example.com/DansCustomURL, I need to fetch their desi ...