Accessing an object from an AngularJS controller in an external function

I previously inquired about this issue and received a suggestion to add a service, but it did not solve the problem. I am trying to access a variable from a controller ($scope) within an external function. Below is a snippet of the example:

app.controller('formContratCtrl', function ($scope, $location, $rootScope,$cordovaFile, $cordovaGeolocation, $cordovaCamera) {

"$scope.owner={
"first":"john",
"last":"kennedy",
"phone":"",
"car":"",
"registration":"",
"dateRegistration":"
};


var JutoPDFCreator = {
createPDF: function(filename) {
var doc = new jsPDF();
doc.text(13, 20, 'First Name : '+ $scope.owner.first);
doc.text(13, 25, 'Last Name : '+ $scope.owner.last);
doc.text(13, 30, 'Phone : '+ owner.phone);
doc.text(13, 35, 'Rented Vehicle : '+ owner.car);
doc.text(13, 40, 'Registered : '+ owner.registration);
doc.text(13, 45, 'Since : '+ owner.dateRegistration);
.
.
} 

Answer №1

I developed a custom service that interacts with an external library in the following manner:

app.service('myPDFService', function() {

  this.generatePDF = function(filename, user) {
    var doc = new jsPDF();
    doc.text(13, 20, 'First Name : ' + user.First);
    doc.text(13, 25, 'Last Name : ' + user.Last);
    doc.text(13, 30, 'Phone : ' + user.phone);
    doc.text(13, 35, 'Rented Vehicle: ' + user.Car);
    doc.text(13, 40, 'License Plate: ' + user.registration);
    doc.text(13, 45, 'Since: ' + user.dateRegistration);

    console.log(user);
  };

});

The service is injected into the controller:

app.controller('formContratCtrl', ['myPDFService', function(myPDFService) {

  this.user = {
    first: "John",
    last: "kennedy",
    phone: "",
    car: "",
    registration: new Date(),
    dateRegistration: new Date()
  };

  this.createDocument = function() {
    myPDFService.generatePDF('filename', this.user);
  };

}]);

For a complete working example visit plunker. Consider using a service to handle the external library as well. If the controllerAs syntax seems unfamiliar, replace this with $scope and inject $scope where necessary.

Angular provides comprehensive documentation on services which can be found here.

Answer №2

To start, you should establish a factory for the external library.

function myPDFFactory() {
    return function() { 
        new jsPDF() 
    };
}
angular.module('yourApp').factory('jsPDF', myPDFFactory);

Next, you can design your custom adapter like this:

MyPDFCreator.$inject = ['jsPDF'];
function MyPDFCreator = function(jsPDF) {
    this.doc = jsPDF();
 }

 MyPDFCreator.prototype.generatePDF = function(filename, owner) {
     this.doc.text(13, 20, 'Name : '+ owner.First);
     . . .
 }
 angular.module('yourApp').service('myPDFCreator', MyPDFCreator);

Finally, just inject the myPDFCreator into your controller and execute the generatePDF() method.

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

The Vue.js component was unable to retrieve the data

I am facing an issue with accessing data inside a simple component. Here is the code for my component: <template> <!-- success --> <div class="message-box message-box-success animated fadeIn" id="message-box-success"> <div cl ...

What is the best way to incorporate AngularJS data into JavaScript for use in Google Chart?

How can I leverage my AngularJS scope data in a Google Chart or JavaScript? Below is my AngularJS file: angular.module('reports').controller('ReportInfoCtrl', ['$scope', 'reports', '$rootScope','$loca ...

The various sections of my website are neatly tucked away under one tab, only revealing themselves to users as they click on each individual tab

My recently published website is experiencing a strange issue. When the site loads, all contents including paragraphs and videos from other pages are displayed under one tab (the HOME tab). However, once any other tab is clicked, the issue fixes itself. Yo ...

What is the best method for preserving HTML content using Ajax?

I am having difficulty storing HTML code in a database using AJAX. Despite having the correct connection information, I am unable to write to the table. <div id="others"> <div id="name"><input type="text" name="results" class="name"> ...

Next.js server component allows for the modification of search parameters without causing a re-fetch of the data

I have a situation where I need to store form values in the URL to prevent data loss when the page is accidentally refreshed. Here's how I am currently handling it: // Form.tsx "use client" export default function Form(){ const pathname ...

What is the most effective method for identifying duplicate values in a multidimensional array using typescript or javascript?

I have a 2D array as shown below: array = [ [ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ] ] I am looking to compare the values in the array indexes to check for duplicates. For example array[0] = [1,1]; array[1] = [1,2]; array[2] = [1,1]; We can see that ...

Struggling with populating a dropdown in MVC with JSON data fetched from an API using jQuery/JavaScript

I am struggling to bind the JSON data retrieved from an API to a dropdown list. I am having trouble extracting the values for id and name from the JSON format shown below: { "categories": [ { "categories": { "id": 1, ...

Ways to access a field value in SAPUI5

As I delve into OPENUI5/SAPUI5, I'm faced with the task of accessing data for the controls I've implemented. For instance: <Label text="Amount" /> <Input id="inputAmount" value="{Amount}" /> <Text id="lblCurrency" text="USD" > ...

Alter the browser's URI without having to reload the page

Is there a way to change the browser URL (or URI) without refreshing the page using HTML5 and HTML5Shiv for IE? For example, if I am currently on http://www.example.com but want to transition to http://www.example.com/4f6gt without the need for a full pa ...

displaying a div as a pop-up within an ASP.NET MVC 4 web application

One aspect of my asp.net MVC 4 application involves a partial view structured like so: <form class="qty-add" action="#" method="POST"> <label>Qty:</label> <div class="inp-controller"> <a href="#" c ...

Implementing gridlines on a webpage using HTML and JavaScript to mimic the grid layout found in Visual Studios

Currently, I have a grid snap function in place, however, I am looking to add light grey lines horizontally and vertically on my Designing application. The goal is to achieve a similar aesthetic to Visual Studios' form designing feature. Utilizing so ...

Guide to switching between 3 classes with mouseover using JavaScript

Currently, I am dealing with an unordered list that contains 4 items. The goal is to have the list grow to 100% of its width when hovered over, while all 'noun hovered li' items should shrink to a width of 0%. Once the cursor leaves, everything s ...

How to include an href in a button using Pug without disrupting a form

Is there a way to create a button that redirects to my /leaderboard page once my quiz app submits? h1 Play Time 4 Trivia! button Go form(method='POST') ul each val in questions li ...

New feature in Safari extension: transferring window object from inject script to global page

Is it possible to transfer the window object from an injected script to a global.html page? I am attempting to pass the window object as part of an object to the global page. However, when I try to dispatch the message from the "load" listener function, i ...

Top recommendation for utilizing $scope variables in Angular applications

Currently, I am working on a new project and I want to ensure that I am correctly utilizing $scope. After watching an informative video on best practices, Miško mentioned that manipulating $scope properties directly may not be the best approach. Typical ...

A function containing a JavaScript Event Listener for better encapsulation

I am encountering an issue with an event listener inside a function where both the listener and emitter are within the same function scope. Upon triggering the event, a variable is supposed to increment. However, when I call the function multiple times, t ...

Looking for giphy link within a v-for loop (Vue.js)

I am fetching a list of movie characters from my backend using axios and rendering them in Bootstrap cards. My objective is to search for the character's name on Giphy and use the obtained URL as the image source for each card. However, when I attemp ...

Transform JavaScript object into desired structure

let obj = { "rec": [{ "id": "25837", "contentId": "25838" }, { "id": "25839", "contentId": "25838" }, { "id": "25838" }, { "id": "25 ...

The tablet is having trouble playing the mp3 audio file

When clicking on an mp3 audio file, I want the previous file to continue playing along with the new one. While this works perfectly on browsers with Windows machines, there seems to be an issue when using a tablet. The second mp3 stops playing when I clic ...

Unable to hide jQuery form and receiving undefined function output

I seem to be facing an issue with one of the buttons. It's not functioning properly. Whenever I click on the "Add Run" button followed by the "Home" button, most functions stop working as expected. The dynamically created form doesn't hide, the ...