Combining an Angular factory with another factory

I'm facing some difficulties with injecting one factory into another.

The error message I'm getting is:

  `ReferenceError: testDataService is not defined`

I thought it would be a simple issue to resolve, but it's turning out to be quite challenging. It seems like I'm struggling with the syntax related to dependency injection.

In my main factory, I'm initializing the service call like this :

   this.treeGridOptions = gadgetInitService.initTreeGridTEST();

Everything looks good up to this point.

However, the problem arises below in initTreeGridTEST

Here's my implementation of the testDataService factory, which just provides some hard-coded options:

 (function () {
'use strict';
angular.module('rage').factory('testDataService', [testData ]);

function testData() {
    var service = {
        treegridData: treegridData
    };
    return service;
}
function treegridData() {
    return {
        "altrows": true,
        "sortable": true,
        "columnsResize": true,
        "editable": true,
        "showToolbar": false,
        "width": "100%",
        "height": 400,
        "source": {}       
    };
}   
})();

and here's where 'testDataService' is being injected:

 (function () {
'use strict';

angular.module('rage').factory('gadgetInitService', ['testDataService', gridHierarchyService]);

function gridHierarchyService(testDataService) {
    var service = {
        initTreeGrid: initTreeGrid,
        initColumnChart: initColumnChart,
        initTreeGridTEST: initTreeGridTEST
    }
    return service;
}
function initTreeGridTEST() {
    var myData = testDataService.treegridData();
    return myData;
}
})();

Any help or advice on this matter would be greatly appreciated,

Bob

Answer №1

testDataService is a variable within the scope of function gridHierarchyService. Accessing it outside the function where it is defined will result in an error. To resolve this, simply move the function initTreeGridTEST inside the factory constructor.

(function () {
'use strict';

angular.module('rage').factory('gadgetInitService',gridHierarchyService);

//Using string notation for dependency injection
gridHierarchyService.$inject = ['testDataService'];

function gridHierarchyService(testDataService) {
//Storing service object in a variable if needed for referring public functions
 return { 
    initTreeGrid: _initTreeGrid,
    initColumnChart: _initColumnChart,
    initTreeGridTEST: _initTreeGridTEST
 }

 function _initTreeGridTEST() {
   var myData = testDataService.treegridData();
   return myData;
 }

}

})();

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

Challenges with ReactToPrint Library and Optimizing Layout for Thermal Printer

Working on a React.js project, I have been using the ReactToPrint library to print a specific section of my page. However, I am facing an issue where the page size remains too large and important content is being left out in the printed receipt. It seems ...

Converting counterup2 to pure vanilla JavaScript: step-by-step guide

Is there a way to convert the counterUp2 jQuery code to vanilla JavaScript? const counters = document.querySelectorAll('.counter'); function count(element) { let currentValue = 0; const targetValue = parseInt(element.innerText); let interv ...

several guidelines assigned to a single element

Exploring two different directives in Angular: 1. Angular UI select - utilizes isolate scope. 2. Custom directive myDirective - also uses isolate scope to access ngModel value. Encountering error due to multiple directive usage with isolate scope. Isola ...

Having trouble inserting an image using Vue?

I am having trouble understanding why only the first image loads, while the others do not. 1. <img :src="require('../assets/batatas.jpg')" :alt="item.title" /> 2. <img :src="'../assets/batatas.jpg'" ...

Sort AngularJS data using multiple select menus

I am trying to create a way to order my data based on multiple select menus. For example: Order : <select ng-model="filterOrder"> <option value="+">- to +</option> <option value="-">+ to -</option> </select> C ...

Arrays data being retrieved and set by Chrome Extension are visible in the console but not appearing in the HTML

Having trouble displaying my arrays in HTML. I'm attempting to do this within a Chrome Extension. While I can view the array perfectly in console.log, I'm encountering issues when trying to add it to the HTML DOM: /* Generating the array f ...

Rounded Corners on an HTML5 Canvas Triangle

Hi there, I'm relatively new to working with HTML5 Canvas and I'm currently attempting to create a triangle with rounded corners. So far, I've experimented with: ctx.lineJoin = "round"; ctx.lineWidth = 20; However, I haven't been suc ...

Converting a Curl command to a JavaScript POST request: best practices

Is it possible to convert the given curl code into a JavaScript post request that will function effectively in all browsers? curl https://connect.stripe.com/oauth/token \ -d client_secret=sk_test_f7PKXx5NRBFG5r41nTrPT7qB \ -d code="{AUTHORIZATIO ...

Understanding the repetition of the X axis in Recharts for ReactJS

I am facing an issue where the X axis on my graph is repeating three times for each month of the year. I have tried adding my data, but the duplication persists. Can anyone provide insight on how to correct this error? What am I doing wrong? Below is a mi ...

It appears that Javascript variables are behaving in a static manner

I am currently building a PHP website with a registration page for users. I am implementing the LOOPJ jQuery Autocomplete script from to enable users to select their country easily. In this process, I encountered an issue where the value of another field ...

Issues with Bootstrap's hamburger menu not functioning properly when clicked

Can't seem to get my hamburger button working. I've followed the bootstrap documentation and ensured that Bootstrap and jQuery are in the correct order, but still no luck. Any suggestions on what could be causing this issue? Are my links misplace ...

AngularJS chatbox widget for interactive communication

Currently, I am in the process of developing the back-end for a web application utilizing angularJS. One of the key features is allowing users to communicate with each other through a pop-up chat box similar to those found in Gmail or Facebook. My goal is ...

Guiding a WordPress Form Submission to a Different Page

I'm currently using WordPress to create a form with the following code: [contact-form][contact-field label='What message would you like to send?' type='textarea' required='1'/]Word Limit: 50 words[contact-field label=&ap ...

Using the .map function on JSON data with and without a parent element in JavaScript

In my current project, I am working on a React + Rails application. For handling JSON data, I typically use the default jbuilder in Rails. However, following the recommendations from the react-rails official documentation, I started adding a root node to m ...

Can JavaScript be used to modify the headers of an HTTP request?

Can JavaScript be used to modify or establish HTTP request headers? ...

Transition from mouse wheel scroll to page scroll not functioning properly when overflow is enabled

The website has a fixed element that uses overflow:auto. Users can scroll this element by positioning the mouse over it. However, once the element reaches the end of its scroll, the page does not seamlessly take over the scrolling. Instead, there is about ...

The Response.Write function is not functioning properly in the production environment

I have created a C# WebService (ASMX) with the code snippet below: if (!SomeValidation()) { //context.Response.ContentType = "application/json"; //context.Response.ContentType = "text/plain"; context.Response.ContentType = "application/text"; ...

Unable to access placeholder information from the controller

I am new to implementing the mean stack. I attempted to view data from the controller, but encountered an error message in the web browser's console. Error: [$controller:ctrlreg] http://errors.angularjs.org/1.6.3/$controller/ctrlreg?p0=AppCtrl Stack ...

How to insert an element INTO a JSON array using JavaScript

I'm having an issue with the way a line is displayed on my screen: Would you like to pay €xx to POS_ID Latte X 1....€2.50-Salad X 1....€4.00-Wrap X 1....€4.50-Coffee X 2....€3.00- My desired format is as follows: Would you like to pay ...

Best practices for sending variables to an HTML page using nodemailer

I am interested in sending an email with an HTML template that includes dynamic data. For example, I want to include a unique id within a link on the page. Is it possible to insert dynamic data into HTML content when sending emails? If yes, I would apprec ...