Is there a way to dynamically switch between AngularJS modules based on a configuration change?

Understanding the inner workings of Dependency Injection with AngularJS modules has sparked an idea in my mind. I thought about leveraging this concept to switch between different modules based on the environment of the application.

For instance, I aim to create a solution that can function on both mobile devices (via Phonegap) and regular desktop browsers.

There is a particular service function I intend to utilize for data access. On the device, I prefer it to query the local database directly. However, for the desktop browser version, I want it to interact with a web service.

To illustrate, I plan to have 2 services that are interchangeable:

angular.module('myDataServiceLocalStorage', [])
.factory('dataSrv', [function () {
return {
getOrders: function () {
// retrieve data from local database
}
};
} ])
;

angular.module('myDataServiceWebService', [])
.factory('dataSrv', [function () {
return {
getOrders: function () {
// fetch data from web service
}
};
} ])
;

In my Angular controllers, I could inject either 'myDataServiceLocalStorage' or 'myDataServiceWebService' to access the getOrders function. But is there a more efficient way to configure this so I can easily switch between them across all controllers?

I'm not necessarily looking for an automatic environment detection mechanism. Instead, I wonder if there's a method to avoid manual module references every time I prepare to deploy the project.

I considered working with providers, but I'm uncertain since their primary role seems to involve modifying existing services before instantiation.

Is achieving such functionality even feasible?

Answer №1

In facing a similar requirement, I took the approach of creating separate factories for each individual device.

app.factory("deviceOneFactory", function(){
   var renderOne = function(params) {
     // Implement logic for rendering typeOneChart
   };

   return {
      render : renderOne
   }
})

app.factory("deviceTwoFactory", function(){
   var renderTwo = function(params) {
     // Implement logic for rendering typeTwoChart
   };

   return {
      render : renderTwo
   }
})

With the above setup, we have two factories returning the same set of function names, effectively implementing an interface.

Additionally, we utilize a parent factory to keep other parts of the application agnostic of this particular section.

app.factory("deviceFactory", function(){

   var localFactory ;

   var deviceFactory = function(){
     switch(devicetype) {
        case 'one':
           localFactory = typeOneDevice;
           break;
        case 'two':
           localFactory = typeTwoDetive;
           break;
        default:
           throw exception("invalid device type : " + deviceType);
     }
   }

   var render = function(params) {
     localFactory.render();
   };

   return {
      render : render
   }
})

Please note that the code provided is not exact, but aimed to give you an understanding of the concept.

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

In Angular, which event can trigger before the browser is refreshed?

onbeforeunload event does not trigger when the page is refreshed. this.scope.$on('$stateChangeStart', (event, next, current) => { if(!confirm("Are you sure you want to refresh this page?")) { event.preventD ...

The JSON response did not contain the expected property in Javascript

Currently, I am developing a weather widget using React that displays temperature and rain forecast. The data is fetched from OpenWeather API and the JSON response structure is as follows: //rainy day 0:{ main: { temp:10} rain: { 3h: 1000} } / ...

Retrieving data from a dynamic form using jQuery

Can someone assist me with the following issue: I have a dynamic module (generated by a PHP application) that includes input fields like this: <input type="text" class="attr" name="Input_0"/> <input type="text" class="attr" name="Input_1"/> ...

Tips for sending a state into the gtm.js function?

As an intern at a startup, I am the sole front-end developer responsible for coding a website in Next.js. My boss has requested that I incorporate Google Tag Manager into the project. Following the example provided by Next on their GitHub page, I have succ ...

Tips on adjusting a standard CSS layout with JavaScript and jQuery to generate a unique ID for the updated style

My CSS contains IDs that look like this: <style> .HIDE-DISPLAY-k { background-color: orange; position: fixed; width: 100%; height: 100%; top: 10px; bottom: 0px; left: 10px; right: 0px; overflow: hidden; } #SHOW- ...

When the button is clicked, update the text within the <script> tags utilizing jQuery, JavaScript, or PHP

Here is the code snippet where changeme represents the text that needs to be replaced upon clicking a button: The following HTML and JavaScript code demonstrates this functionality: 1) Any input provided by the user in the field will be captured, replaci ...

Locate a specific sequence of characters within an array of objects using JavaScript

I am working with an array of objects, where each object contains a string value. My task is to search for a specific substring within the string. [ { "link": "https://www.sec.gov/Archives/edgar/data/1702510/000170251022000084/00 ...

Using JavaScript, insert a new date row onto a JSP page

When I click on a hyperlink, I want to add a new row to a jsp page. The functionality is working correctly, but the date function class="dateTxt" is not functioning in the new row. Below are the details of the javascript and jsp function. Javascript: fun ...

PHP: Eliminating Line Breaks and Carriage Returns

My content entered into the database by CKEditor is adding new lines, which poses a problem as I need this data to be rendered in JavaScript as a single line of HTML. Within my PHP code, I have implemented the following steps: $tmpmaptext = $map['ma ...

Sending information from Vue to Express for processing

Is there a way to pass data from Vue to an express server? For example, in the scenario below, I am looking to send the data logged in my Vue function to the "id" variable on the server side. expressApp.post('/delete' , function (request, respons ...

What is the best way to interact with Redis without using any external modules?

I am curious about the communication process between the node redis wrapper and the RESP (REdis Serialization Protocol) database. Here is a simple example: const redis = function(uri) { this.client = '' // How do we establish a connection wit ...

Tips for removing the "" character from a JSON string using JavaScript

At my node js server, I am receiving a json string that has the following format: {\"gID\":1,\"sID\":18,\"T\":\"Parking\"} I added the "\" in the string because it was created in C and the \ is used to es ...

Next.js and Material UI - issues with dynamic styles not functioning

I recently started using Next JS in combination with Material UI, following the example project setup provided in the documentation on Github: https://github.com/mui-org/material-ui/tree/master/examples/nextjs My main objective is to utilize Material UI&a ...

Triggering JavaScript events using jQuery

I am experiencing an issue with an input element that triggers a modal containing a table when clicked. From this table, you can select a line and a JavaScript function modifies the value of the input element accordingly. However, I am trying to detect the ...

Creating an axios URL using Vue data results in receiving the value of undefined

I'm currently experimenting with axios to retrieve data from openweathermap. I've been working on constructing the URL by utilizing various methods to extract latitude and longitude from the user's browser, followed by a function call to pie ...

% unable to display on tooltip pie chart in highcharts angular js

https://i.stack.imgur.com/Ccd7h.png The % symbol isn't displaying correctly in the highcharts ageData = { chartConfig: { options: { chart: { type: 'pie', width: 275, height: 220, marginTop: 70 ...

Change the color of a c3js chart when it loads

I have been searching for a way to customize the color of a scatter chart's plot, and I came across an example that uses d3 code within the chart http://jsfiddle.net/ot19Lyt8/9/ onmouseover: function (d) { d3.select(d3.selectAll("circle ...

Attempting to develop a next.js web application using Vercel has hit a roadblock for me. Upon running the "vercel dev" command in the terminal, an error message is

vercel dev Vercel CLI 28.5.3 > Creating initial build node:events:491 throw er; // Unhandled 'error' event ^ Error: spawn cmd.exe ENOENT at ChildProcess._handle.onexit (node:internal/child_process:285:19) at onErrorNT (nod ...

Building nested routes in a protected path using react-router version 6

At the moment, I am utilizing react-router-dom version 6.1.1 and I have a private route in use. Typically, within this private route, I include other routes to maintain my Sidebar. This is how my code appears: // App.tsx const RequireAuth: React.FC<P ...

Executing a command efficiently in Javascript with the get method

The command that needs to be sent to the embedded device is in the form of a GET method. However, the value continuouspantiltmove: String(pt) is not being properly transmitted to the CGI script through Google Chrome, causing it to fail. Since I do not hav ...