Can two controllers be used for the main-app and sub-app with the same URL using angular ui-route?

I have implemented two controllers, 'BaseController' and 'SubController', for my main application and sub-application. Both controllers are configured to point to an empty URL.

Below is the configuration for the main application:-

angular.module("main-app").config(["$stateProvider", "$urlRouterProvider", function ($stateProvider, $urlRouterProvider) {
  $stateProvider
  .state('base', {
      url: "",
      views: {
        "base": {
          controller: 'BaseController' 
        }
      }
    });
}]);

And here is the configuration for the sub-application:-

 angular.module("sub-app").config(["$stateProvider", "$urlRouterProvider", function ($stateProvider, $urlRouterProvider) {
  //$locationProvider.html5Mode(true); 
  $stateProvider
  .state('sub', {
      url: "",
      views: {
        "patients": {
          templateUrl:"templates/scope/patients/patients_search.html",
          controller: 'PatientsController' 
        }
      },
    });
}]);

The main application includes the sub-application.

How can I ensure that both controllers are loaded with the same empty URL?

Answer №1

Having two controllers for the same root view may not be the most logical approach. A controller typically requires a specific view context to operate effectively within the scope hierarchy of $scope.

An alternative solution could involve abstracting your controllers into services that can be injected into any controller. Consider creating services such as mainsrv and subsrv, then utilizing a single root controller with url: ''. Here is an example of how you can define your root controller:

angular.module('myapp', [])
    .controller('AppCtrl', ['mainsrv', 'subsrv', function(mainsrv, subsrv){
        // use mainsrv and subsrv services here
    }]);

If you do have a genuine need for multiple controllers to load on the root view, you can still create a single root view but utilize ng-controller in each individual view to specify the context for each controller. For instance:

<div ng-controller="BaseController"></div>
<div ng-controller="PatientsController"></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

Tips for efficiently printing invoices on specific paper: Print a maximum of 20 items per sheet, and if it exceeds this limit, continue onto the next page. Ensure the total amount is

$(document).ready(function(){ var j = 23; for (var i = 0; i < j+11; i++) { if (i != 0 && i % 11 == 0) { $("#printSection div").append("<?php echo '<tr><td>fff</td></tr>'; ?>"); ...

Tips for choosing an image using jQuery from an external HTML page

I'm attempting to embed an HTML page within a div and then individually select all the img tags within that page to display an overlay div on top of the images. Currently, I can insert the HTML into a div named "asd" and it seems like the jQuery is f ...

Express/NodeJS encountering a CORS problem, causing services to be inaccessible in Internet Explorer

Currently, I am working on a REST-based service implemented in Express/NodeJS. The code includes CORS (Cross Origin Resource Sharing) implementation to allow services to be consumed from browsers like Chrome and Firefox. However, there seems to be an issue ...

An issue has been encountered with the default selection in a dropdown menu

Struggling to make the initial option of a select box "selected" upon page load. Check out the code on Plunker In the provided plunker example, the select box appears empty when the page loads even though the deal model has a default category value. What ...

Unable to send POST request (including data) using event trigger from an external component

I'm currently facing an issue where a click event in one component is triggering a method in another, but the data that should be passed in my POST request isn't being sent. Interestingly, when I test the functionality by calling the method dire ...

Angular 8: How to Retrieve Query Parameters from Request URL

Can I retrieve the GET URL Query String Parameters from a specific URL using my Angular Service? For example, let's say I have a URL = "http:localhost/?id=123&name=abc"; or URL = ""; // in my service.ts public myFunction(): Observale<any> ...

The mongoose.populate() method is failing to display the populated content

// defining user schema const mongoose = require('mongoose'); const {ChatRoom} = require('./chatRoom'); const userSchema = new mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, username:{ type: 'String', unique ...

The metro bundler is facing an unexpected glitch and is stuck in the terminal, failing to load

Recently, I've been using explo-cli to work on a react native project. Everything was running smoothly until today when I encountered an error stating that it couldn't find module './iter-step'. Before this, there was also an issue with ...

Trouble with triggering events from Datatable buttons

Below is the code snippet I am currently using for my DataTable : var oTable12= $('#example').DataTable({ "aaData": tableData, "aLengthMenu": [[5, 10, 20, -1], [5, 10, 20, "All"]], "iDisplayLength": 5, "aoColumnDefs ...

Problem with Ionic 2 local storage: struggling to store retrieved value in a variable

Struggling to assign the retrieved value from a .get function to a variable declared outside of it. var dt; //fetching data this.local.get('didTutorial').then((value) => { alert(value); dt = value; }) console.log("Local Storage value: " ...

problem with the clientHeight attribute in window event handlers

The component below is designed to react to changes in window resize based on the container height. However, there seems to be an issue where the containerHeight variable increases as the window size decreases, but does not decrease when I make the window ...

Tips for retrieving the ID of a dynamic page

In my Higher Order Component (HOC), I have set up a function that redirects the user to the login page if there is no token. My goal is to store the URL that the user intended to visit before being redirected and then push them back to that page. However, ...

Incorporating numerous dropdown menus to a table filled with data retrieved from a database

I have implemented a dynamic table that adds a new row at the end when a button is clicked. One of the columns in the table contains a dropdown list, and I want this dropdown list to display values from a database. This is how I am constructing my table ...

Anticipate the completion of Subject callback execution

Take a look at the code snippet below: const mA = async () => { try { const subscription = myEmitter.subscribe(url => getD(url)); const la=()=>{...}; return la; } catch (error) { throw error; } }; ...

How do I incorporate scrolling into Material-UI Tabs?

I am currently incorporating Material-ui Tablist into my AppBar component. However, I am facing an issue with the responsiveness of the tabs. When there are too many tabs, some of them become hidden on smaller screens. For more information on the componen ...

Performing subtraction on two arrays in Javascript

Is there a way to eliminate all duplicate elements from one array list that are also present in another array list using the .filter() method of ES6 javascript? I am open to solutions in jQuery as well, but they must be compatible with IE11+ and Chrome fo ...

Seeking a solution for inserting input values into a JSON file within a node.js environment

As I was developing my new project, a to-do list web application, Below is the code snippet from 'todo.html' : <html> <head> <title>My TODO List</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

transferring double quotation marks and square brackets through a parameter

I have an angularjs (1.x) scope set up as follows: $scope.report = { resource: '/public/emplyACH', params: { "employeeId": [78] } }; When I try to access it using console.log (console.log(scope.parms)) I see the output as ...

Learn how to retrieve information using the dash operator in ReactJS

I find it a bit amusing, but I'm encountering an issue. Can anyone lend me a hand with this? So, I'm using an API to fetch some data and it appears that the response from the API is in this format: start-time:2323232 end-time:2332323 Now, when I ...

Is it possible to retrieve 2 arguments within a function in a non-sequential manner?

Let's say there is a function with arguments A, B, C, D, and E. Function(A, B, C, D, E) However, not all arguments are needed all the time. For instance, only A and C are needed in some cases. Currently, I would have to call the function like this: Fu ...