Lazy loading of AngularJS modules allows for deferred loading of code

When working on my project, I decided to separate angular services into different files. Each file or service should be a part of a shared module called 'com.mysite.services'. For example:

  • ServiceA.js
  • ServiceB.js
  • ServiceC.js

But when defining them like this:

angular.module('com.mysite.services', []).
    service('ServiceA', function()
    {
    });

I found that this was overwriting the module for each file. To fix this issue, I created a wrapper function that would check if the module is defined and return a reference to it, or create the module if it didn't exist:

function angular_module(name, deps)
{
   var m;
   try
   {
     m = angular.module(name);
   }
   catch (e)
   {
     m = angular.module(name, deps || []);
   }
   return m;
};

So, to address this problem, I simply replaced the "." with "_" in the module declaration:

angular_module('com.mysite.services', []).
        service('ServiceA', function()
        {
        });

This workaround worked for me, but it made me wonder: is there an Angular-friendly solution to avoid using my custom wrapper function?

Answer №1

If you're unsure if this solution will meet your needs, consider implementing the following steps:

Start by creating a separate file called Bootstrap.js and populate it with the code below:

// Bootstrap.js
angular.module('com.mysite.services', ['com.mysite.services.ServiceA', 'com.mysite.services.ServiceB', ....]);

Next, for each service, follow this structure:

// ServiceA.js
angular.module('com.mysite.services.ServiceA', []).
   service('ServiceA', function(){});

//ServiceB.js
angular.module('com.mysite.services.ServiceB', []).
   service('ServiceB', function(){});

By depending on 'com.mysite.services' in your application, all of your services will be easily accessible.

Answer №2

To start building your app, begin by creating an App.js file:

var myAppModule = angular.module('com.myapp.services', []);

In ServiceA.js, define the ServiceA module within myAppModule:

myAppModule.service('ServiceA', function()
    {
    });

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

Scraping data without a browser: Selenium, phantomJS, and Geb

I have a task of extracting data from a website on a weekly basis. The data is only visible after clicking on the page (triggering a Javascript function). It is loaded into a table which can be identified by its unique ID. This script needs to be executed ...

Ways to implement shader on a THREE.Object3D that has been loaded using OBJMTLLoader

After loading a model with THREE.OBJMTLLoader, I want to add a vertex and fragment shader to it. var loader = new THREE.OBJMTLLoader(); loader.addEventListener('load', function(event) { var mesh = event.content; scene.add(mesh); }); load ...

Navigate to a New Page post Dropdown Selection

Currently working on developing a website using Github Pages where I need users to be directed to a specific page after choosing the final option. I am extracting data from a JSON file. I attempted to include an anchor tag in the JSON but it does not red ...

The jQuery selector threw an Uncaught SyntaxError due to an Unexpected identifier

Just starting out with programming, I'm attempting to send data using my Python script. I'm unsure of what the error message is indicating. $(document).ready(function() { $("tags").keyup(function({ var search = $("tags").val() $.post(" ...

What is the proper way to type a collection and put it into action?

I am looking for a way to create an object that mimics a set. Specifically, I want the transaction id to act as a key and the transaction details as the value. To achieve this, I created the following: type TransactionDetail = { [key: TransactionId]: Tra ...

Do JavaScript objects need to be encapsulated?

Currently in the process of developing a node.js application and in search of methods to establish the datamodel. The JSON format is utilized for data transmitted to and from the client, while communication with the MongoDB database is also done using JSO ...

Using JQuery to create animations with fadeIn and fadeOut effects is a great way to

As a complete newbie taking my first steps in front-end development, I spent most of my day trying to work out an animation function but couldn't quite get it right. Below are the snippets of HTML, CSS, and JavaScript codes: <!DOCTYPE html> < ...

Adjust Vue FilePond dimensions

I am currently working with a Vue Filepond and trying to ensure that it fills the height of its container. My Vue Filepond setup also involves Vuetify. Whenever I attempt to set values in the CSS, they are constantly overridden by 76px. Although fill-hei ...

Problems with implementing JavaScript code in a WebView

I am currently working on an android WebView project where I have managed to change the background color to orange with this code snippet. @Override public void onPageFinished(WebView view, String url) { wv.loadUrl("jav ...

When running "pm2 serve build PORT", the error message "404 page not found" is displayed

After completing the tutorial at https://reactjs.org/tutorial/tutorial.html, I uploaded my project to a production server running on Ubuntu with Nginx and SSL. I used npm run build to create the build files and served them as static files using the serve m ...

A React component making a GET request with a delay of one or more clicks

Trying to explain this may be a bit tricky, but essentially, when a user clicks on a component, I trigger a GET request to fetch data for another component. However, this request is only made after a few clicks. I must admit, I'm not entirely sure if ...

Display content exclusively to users

I am using Devise to allow users to log in through Facebook or create an account on my website. Once logged in, they have the ability to add movies to their front page. However, the issue is that every user can see all the movies instead of just the ones t ...

Creating a dynamic dropdown menu based on a class value using JavaScript in PHP

There are two dropdown menus on my webpage that display information from my SQL table. The first dropdown contains different "Colors," and the second dropdown contains members associated with each color group. Each member is categorized into different optg ...

The functionality of $location.path() seems to be malfunctioning when it comes to scroll

angular.module('example').service('myService', function myService($rootScope,$route,$http,$location) { $("#mainwindowscroll").on('scroll', function (e) { $location.path('/about&apo ...

Attaching an event listener to elements with a specified Class name

Currently facing a challenge where I am trying to implement a function that captures click events on squares. The objective is to capture the click event on every button with the square class. import { Component, OnInit } from '@angular/core&apos ...

The requested resource in AngularJS does not have the 'Access-Control-Allow-Origin' header present

How can I access an API with AngularJS? For example: footballdataAPI.getTeams = function() { $http.defaults.headers.common['Auth-Token'] = '613a6b6937394ae8a94d69f358f76902'; return $http.get('http://www.football ...

Tips for passing an object by value to an Angular2+ component

Imagine having a scenario where I create a component that takes a Foo instance and generates a form for editing. export class ChildComponent implements OnInit { @Input() foo : Foo; @Output() onChange : EventEmitter<Foo> = new EvenEmitter<Foo& ...

Utilizing a search bar with the option to narrow down results by category

I want to develop a search page where users can enter a keyword and get a list of results, along with the option to filter by category if necessary. I have managed to make both the input field and radio buttons work separately, but not together. So, when s ...

Can a promise notify callback return a value?

Can a promise notify callback return a value? The code below demonstrates how ServiceB.Start returns a deferred promise with the deferred defined within ServiceB: ServiceB.Start(action).then( function() {console.log("Success");}, functi ...

Exploring the realm of Angular templating and routing combined with the power

Currently, I am in the process of developing my very first Angular website that involves templating and routing. My goal is to have an image on the page that spans the entire window size minus 70 pixels. //Using Jquery (This particular section functions ...