Leverage the Power of Two AngularJS Factories

Can I efficiently use two Factories in AngularJS by calling one from the other?

Here's the Scenario:

I have a Factory that returns an Array. This Factory is responsible for checking if the data to populate this Array already exists in local SQL Storage.

If it is TRUE, it sends this Data back to my Controller.

If it is FALSE, it should then invoke another Factory that fetches Data from a RESTful API. The retrieved Data is then stored in WebSQL DB and finally returned.

Is this Design based on standard Software-Patterns? I am struggling to implement AngularJS Techniques in my Project...

Answer №1

Injecting one service/factory/provider into another is perfectly acceptable.

To determine when to use each type, check out this informative answer - AngularJS: Service vs provider vs factory

In the specific scenario mentioned, it is suggested to have separate services for SQL and API functionality. The controller should only inject the SQL service and pass data to it. The SQL service decides how to handle the data; if necessary, it can retrieve additional information from the API service, which should return a promise initially and provide data upon resolution. Once the SQL service completes its operations, it sends the processed data back to the controller, regardless of whether it interacted with the API service or not. It is recommended to employ the promise pattern throughout this process. The controller does not need to be aware of the details regarding the API.

Answer №2

It is perfectly acceptable for two factories to exchange services with each other.

Answer №3

One of the great features of AngularJS is its built-in dependency injection mechanism, which allows for easy sharing of resources. For example, if you have two factories that need to use each other, here is a simple example of how to achieve this:

var app = angular.module('custom-factoryApp', ['ngRoute']);
app.factory("myFactory1", function() {
    return "Controller";
});

app.factory("myFactory2", function(myFactory1) {
    return "factory" + myFactory1;
});
function customController($scope, myFactory2) {
    $scope.ctrlName = myFactory2;
}

Now, let's take a look at the view:

<div ng-app="custom-factoryApp" class="container">
    <div ng-controller="customController" class="page-content">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header>
                    <h3 class="modal-title>AngularJS Custom Factory Example</h3>
                </div>
                <div class="modal-body>
                    {{ctrlName}}
                </div>
            </div>
        </div>
    </div>
</div>

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

Is there a way to automatically change the value of one input box to its negative counterpart when either of the two input boxes have been filled in?

Consider two input boxes: box1 box2 If a user enters a number in one of the input boxes, we want the value of the other input box to automatically change to the opposite sign of that number. For example: User enters 3 in box1. The value of box2 shoul ...

Validation is not being enforced for the input field labeled as 'name' in the form

Can anyone assist me with a form validation issue I'm encountering while working on my project? The validation is functioning correctly for email and institution fields, but it seems to be ignoring the name field. Any suggestions or help would be grea ...

Experimenting with Selenium to automate processes involving dynamic class attributes

My issue involves a Button class = "searchbar__SearchButton-sc-1546roh-3 searchbar__CancelButton-sc-1546roh-4 glEceZ" I am attempting to locate this element in the browser using return browser.element('button[class^="searchbar__CancelButton-"]&ap ...

The error message "Google Heatmap API - visualization_impl.js:2 Uncaught (in promise) TypeError: Cannot read property 'NaN' of undefined" was encountered while using the

I'm currently working on a project that involves utilizing a JSON data structure like the one shown below: [ { "lat": 53.1522756706757, "lon": -0.487157731632087, "size": 63, "field": "TestField", ...

HTML link with "mailto:" not opening in a new tab

Just posted for the first time! I'm attempting to create a mailto link using 'templated' JavaScript that pulls specific data from a JSON object: var menu = { "menu": [ { "title": "let's talk", "link": "mailto:<a href ...

The behavior of Ajax is resembling that of a GET method, even though its intended method

Greetings, I am currently facing an issue while coding in Javascript and PHP without using jQuery for Ajax. My aim is to upload a file over Ajax and process it in PHP. Here is the code snippet: index.html <html> <head> <title>PHP AJAX ...

Transforming a JavaScript object into a different shape

I need help converting a list of team objects containing team names, reporters, and statuses for each day into date-based objects with all teams and their respective statuses for each date. I attempted the following code snippet but did not achieve the de ...

JavaScript Failing to Validate User Input in Form

I'm a beginner in JavaScript and I'm trying to validate a simple date of birth input, but for some reason, it seems that the JavaScript file is not working. No matter what I input, it always goes through, so I'm trying to figure out what&apo ...

Can multiple groupings of objects be viewed in a JSON file?

Currently, I am interested in creating a leveling system without relying on a database. While I understand that using a database is the more efficient approach, my server doesn't have a large user base and I have yet to learn how to work with database ...

Is there a way to determine the position of the highlighted text within a textarea?

Is there a simple way to calculate the position of the selected text within a textarea using vanilla JavaScript or Angular (possibly with a directive)? This is important in order to display a div with a popup above the selected text. Coordinates are need ...

Sending a null value through AJAX to a controller

I've been working on adjusting my save routine to pass a null value to id_cellcarrier in my codeigniter controller. The code snippet below showcases what I've attempted so far, but it doesn't seem to be functioning correctly. I'm omitti ...

JSON to URN Converter: A tool for converting JSON references

Is there a way to convert URL references to JSON and back again programmatically? (include:(and:List((or:(urn:li:adTargetingFacet:locations:List(urn:li:geo:102221843)) ),(or:(urn:li:adTargetingFacet:skills:List(urn:li:skill:17)))))) Are there any JavaScri ...

What is the best way to position an image in the center of the screen with uniform margins around it?

Could someone please help me figure this out? I've been attempting for some time but can't seem to make it work with the bottom margin. This website in the fashion industry showcases what I'm trying to achieve: It's designed to be resp ...

The directive fails to refresh when there are modifications made to the service model

My application's model is stored in a service: angular.module('adminClient').factory('myApi', function () { var model = {}; model.myObject = { label: 'New York City' }; return { model: fu ...

Redirecting pages using an Ajax script in JavaScript

Unfortunately, I am unable to use a *.php extension for my page due to unforeseen circumstances. This has led me to consider using *.html instead and implementing conditional redirection using javascript/Ajax to call a PHP script that can evaluate the cond ...

Error encountered while scrolling with a fixed position

I am currently in the process of developing a carousel slider that resembles what we see on Android devices. The main challenge I am facing at this early stage is applying the CSS property position: fixed; only horizontally, as vertical scrolling will be n ...

While it is possible to filter by friend.brand.id within friends in Angular, unfortunately the || undefined trick cannot be used to reset the filter when it is NULL

In the futuristic world of 2075, immortal humans have subjugated mortal humans. There exists a unique store where mortal friends are sold, and efforts are being made to develop an app that allows customers to manage their friends based on their favorite br ...

Increased Z-index on an unfamiliar site

I'm in the process of enhancing the Moodle platform at my school with a userscript, and I want to create a sleek UI for it. One feature I want to add is a progress bar that stays fixed at the top of the browser viewport so that it remains visible as ...

Store information in Factory and retrieve it in the controller

I am encountering an issue with my code. Below is the factory code: .factory('shareDataService', function() { var sharedData = {}; sharedData.shareData = function(dateFrom, dateTo) { var from = dateFrom; var to = dateTo ...

What is the best way to set up prettier in VSCODE so that it organizes jsx attributes across multiple lines?

My preference is for the following syntax: <input id="inputForEmail" type="email" className="form-control" aria-describedby="Enter email address" placeholder="Enter emai ...