Running different AngularJS applications on a single webpage

I am currently working with two separate apps on a single page.

Navbar Module

This module is situated in the navbar of the page and is included on every page of the application through the master layout file (using Laravel). It contains functions like search, logout, and login.

Posts Module

This module is only displayed on the Dashboard page of the application. It loads and displays posts from the backend.

Both of these apps are currently loaded separately using angular.bootstrap. However, they both require the use of a common service called UserService. This service retrieves details of the logged-in user and is part of a different module called myapp.utils. The issue is that when I inject the service into both apps, the User object is created twice, which is not desired. The code snippet provided shows the log being printed twice in the console.

.factory('UserService', function(){
    console.log("Initializing UserService");

    return {
        'User':...
    }
})

Combining both apps into a single larger module is not an option since they are declared in two different blade templates (server view files).

I am seeking alternative strategies to resolve this issue. Any suggestions would be appreciated.

Answer №1

By utilizing an Immediately Invoked Function Expression (IIFE) to create a singleton, along with the .factory() method in your shared module, you can ensure that the singleton is instantiated only once.

The challenge arises when you require a service that is unique per Angular app, such as $rootScope or $rootElement. In such cases, you may need to pass these services into the function of the shared service that utilizes them, which can be cumbersome.

Below is a demonstration that mimics this scenario effectively:

var timesInstantiated = 0;

(function() {
  var singletonInstance = null;

  function MyService($filter) {
    this.$filter = $filter;
    console.log('Creating sharedSvc instance');
    timesInstantiated++;
  }

  MyService.prototype.strikeItRich = function() {
    return "I just found " + this.$filter('currency')(20, '$');
  };

  angular.module('shared', [])
    .factory('sharedSvc', function($filter) {
      if (!singletonInstance) {
        singletonInstance = new MyService($filter);
      }
      return singletonInstance;
    });
})();


var topApp = angular.module('topApp', ['shared'])
  .run(function($rootScope, sharedSvc) {
    $rootScope.topMessage = "I'm on top of the DOM (hey oh)";
    $rootScope.sharedMessage = sharedSvc.strikeItRich();
  });

var bottomApp = angular.module('bottomApp', ['shared'])
  .run(function($rootScope, sharedSvc) {
    $rootScope.bottomMessage = "Bottom's up! (Who switched gravity?!)";
    $rootScope.sharedMessage = sharedSvc.strikeItRich();
  });


document.addEventListener('DOMContentLoaded', function() {
  // bootstrap both modules
  console.log('Bootstrappin\'...');
  angular.bootstrap(document.getElementById('top-app'), ['topApp']);
  angular.bootstrap(document.getElementById('bottom-app'), ['bottomApp']);

  document.getElementById('times-instantiated').textContent = timesInstantiated;
}, false);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>

<div id="top-app">
  <h3>Top App</h3>
  <p>Top Message: {{topMessage}}</p>
  <p>Shared Message: {{sharedMessage}}</p>
</div>
<div id="bottom-app">
  <h3>Bottom App</h3>
  <p>Bottom Message: {{bottomMessage}}</p>
  <p>Shared Message: {{sharedMessage}}</p>
</div>
<hr/>
<p>Times shared service instantiated: <span id="times-instantiated">?</span></p>

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

What is the best way to create reusable Javascript code?

Lately, I've adopted a new approach of encapsulating my functions within Objects like this: var Search = { carSearch: function(color) { }, peopleSearch: function(name) { }, ... } While this method greatly improves readability, the challeng ...

Steps for registering a function on $rootScope when angularjs is ready

In order to make a method accessible throughout angularjs, I am looking to register it with 2 arguments (the resource id and the delete callback) using the resource provider to handle the deletion process. To properly register this method, I need angularj ...

Steps for calling a function in index.js using Node.js

I am just starting to learn about NodeJS and I have a question that might seem basic to some, but I would really appreciate some assistance here. Here is the content of my index.js file:- 'use-strict'; const { myauth } = require('./src/au ...

Incorporate stateProvider views across all modules for seamless navigation between different

Is there a way to use a stateprovider view template across all modules seamlessly? In my index.html file, I have the following setup: <div ui-view="nav"></div> <div ui-view></div> <div ui-view="footer"></div> My confi ...

What is the best method for obtaining a spring controller's object using AJAX?

Here is the AJAX call I am working with: var url = "UsersGroupReader.html?selectedCompanyName=" + selectedCompanyName + "&test="+Math.random(); req.onreadystatechange = processAccessGroupRequest; req.open("GET", url, true); req.send(null); function ...

Ways to retrieve the final appearance of element m in array n

As a beginner in programming, my goal is to access the last position of element m within array n. The following code displays all positions of element m: var n = []; while (true) { let input = prompt("Please enter a number for the ...

Combining Django and chartjs to create stacked multiple charts

Hey there! I'm working on a Django application and using Chart.js to create bar charts. I encountered an issue where, after generating a new chart with a button click, the old one still lingers behind when hovering over the new chart. I have a suspici ...

implementing conditional logic in angularjs expressions

<p>{{isExisted}}</p> Looking to show either "Active" or "Inactive", but the isExisted variable only returns true or false. Need help with setting up a conditional if else statement to change it to the desired value. ...

Is it possible to use Gulp.js to serve src files without browserSync enabled?

Started a fresh project using Yeoman Gulp-Angular generator. I grasp the concept of BrowserSync, but I simply cannot fathom why anyone would put up with their network requests being overwhelmed by it: I am inclined to eliminate BrowserSync from my projec ...

How can I use regular expressions to validate one-letter domain names?

I am in the process of developing a validation rule for my C# MVC Model using Regex. [RegularExpression(@"(\w[-._+\w]*\w@\w{1,}.\w{2,3})", ErrorMessage = "* Email Address: Please enter a valid Email Address.")] public virtual stri ...

Exploring the power of JQuery's $.post() function and the magic

In order to utilize the GroupMe API (), the following command is required: $ curl -X POST -H "Content-Type: application/json" -d '{"source_guid": "frgfre", "text":"alala"}' https://api.groupme.com/v3/groups/ID/messages?token=YOUR_ACCESS_TOKEN I ...

"Enhance your website with autocomplete feature using the power of jQuery 1.4.2 and jQuery UI 1

Struggling to make jQuery autocomplete work. Despite searching for examples, most seem outdated. Modeled after a good example from the jQuery UI site but still can't get it to display data. My JSON data source is accessed via URL. [{ "pk": 1, "mo ...

Tips for showing and modifying value in SelectField component in React Native

At the moment, I have two select fields for Language and Currency. Both of these fields are populated dynamically with values, but now I need to update the selected value upon changing it and pressing a button that triggers an onClick function to update th ...

Utilizing AngularJS to create a relational database representation from REST api

I'm working on an app that utilizes a combination of Node.js with MySQL for the backend and AngularJS for the frontend. While I have successfully set up the backend REST service, I am struggling with how to model my relational data effectively. Some q ...

Incorporating external JavaScript into a Rails application

Having trouble with the syntax on this simple problem. Struggling to find examples of externally linked files, all solutions online involve storing a local copy instead. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" typ ...

The variable being attempted to read is undefined, resulting in an error

I am attempting to access the title property of the first item in an array of objects. Interestingly, when I manually enter the following code in Chrome's JavaScript developer console: hello.example.array[0].title I successfully retrieve the title. ...

Error message "invalid function call this.job.execute" when using Node.js node-schedule npm package

Having just started with nodejs, I created a nodejs program and set it to run every minute using the node-schedule library. However, after running for some time and producing several logs in the console, I encountered an error stating that this.job.execute ...

What causes a component to not update when it is connected to an Array using v-model?

Array1 https://i.stack.imgur.com/cY0XR.jpg Array are both connected to the same Array variable using v-model. However, when changes are made to Array1, Array2 does not update. Why is this happening? Process: Upon examining the logs, it can be observed th ...

This TypeScript error occurs when trying to assign a value of type 'null' to a parameter that expects a type of 'Error | PromiseLike<Error | undefined> | undefined'

Currently, I am making use of the Mobx Persist Store plugin which allows me to store MobX Store data locally. Although the documentation does not provide a TypeScript version, I made modifications to 2 lines of code (one in the readStore function and anot ...

Take out the bottom of the structure

Currently, I am utilizing ThreeJS to showcase a house model. My goal is to create a grassy area surrounding the house. However, I have encountered an issue where if the grass is simply a flat plane, it ends up appearing inside the house itself (as seen in ...