How to manage multiple controllers for the same template in AngularJS?

I am facing a requirement where a single page needs to display a lot of different data, all within one vertical-scrolling page.

To manage this, I have implemented collapsible divs on the page controlled by ng-if to efficiently handle the DOM elements.

In the initial prototype, I had all the logic for these divs in one controller. However, I have now decided to take a different approach. I want to have one main controller for the entire page and separate child controllers for each collapsible div.

I have created an object for each div in the page controller and added multiple child controllers in my main module (app.js). I expected each of them to be children of the pageCtrl so that I can access the data for each div from there.

Unfortunately, this setup is not working as expected. There are no errors in the console, but none of the divs are visible.

The structure of my code is as follows:

<body ng-app ="mainModule">
 <div ng-controller ="pageCtrl">
    <div ng-controller = "collapse1Ctrl" ng-include="collapse1.tpl" ng-if="collapse1reqd">
<div ng-controller = "collapse2Ctrl" ng-include="collapse2.tpl" ng-if="collapse2reqd">
<div ng-controller = "collapse3Ctrl" ng-include="collapse3.tpl" ng-if="collapse3reqd">
<div ng-controller = "collapse4Ctrl" ng-include="collapse4.tpl" ng-if="collapse4reqd">
<div ng-controller = "collapse5Ctrl" ng-include="collapse5.tpl" ng-if="collapse5reqd">

</div>

My JavaScript code looks like this:

angular.module("mainModule", []);
angular.module("mainModule").controller("pageCtrl", pageCtrlFn);
angular.module("mainModule").controller("collaspse1Ctrl", collaspse1CtrlFn);
angular.module("mainModule").controller("collaspse2Ctrl", collaspse2CtrlFn);
angular.module("mainModule").controller("collaspse3Ctrl", collaspse3CtrlFn);
angular.module("mainModule").controller("collaspse4Ctrl", collaspse4CtrlFn);
angular.module("mainModule").controller("collaspse5Ctrl", collaspse5CtrlFn);

I have checked that all templates and conditions are correctly placed.

Due to the length of my code, I am refraining from posting it at the moment. I may create a similar fiddle to share soon.

At this point, I am questioning if there might be an issue with the overall structure of my implementation. Any insights would be greatly appreciated!

Answer №1

After carefully analyzing the original poster's question and the challenges faced, here is a demo showcasing how nested controllers function and how the scope behaves. You can view the example here.

Here is how the HTML structure looks:

<body ng-app="scopeInheritance">
<div class="spicy">
    <div ng-controller="MainController">
        <p>Good {{timeOfDay}}, {{name}}!</p>
        <p>{{display.showName}} - {{age}} --> New Age - {{display.age}}</p>
        <input type="text" ng-model="name">

        <button ng-click="resetTime()">CHANGE</button>
        <div ng-controller="ChildController">
            <p>Good {{timeOfDay}}, {{name}}!</p>
            <button ng-click="setTime()">SET</button>
            <input type="text" ng-model="display.showName"> Age - {{age}}
            <input type="text" ng-model="age">
            <button ng-click="setAge()">Change Age</button>
            <div ng-controller="GrandChildController">
                <p>Good {{timeOfDay}}, {{name}}!</p>
            </div>
        </div>
    </div>
</div>

The JavaScript implementation is as follows:

(function(angular) {
  'use strict';
var myApp = angular.module('scopeInheritance', []);
myApp.controller('MainController', ['$scope', function($scope) {
  $scope.timeOfDay = 'morning';
  $scope.files ='';
  $scope.name = 'Nikki';
  $scope.display={};
  $scope.display.showName ='Vikram';
  $scope.age ='20';

  $scope.resetTime = function(){
     $scope.timeOfDay = 'chaged day';
   };

}]);

myApp.controller('ChildController', ['$scope', function($scope) {
  $scope.name = 'Mattie';
   $scope.$parent.timeOfDay ='';
   $scope.setTime = function(){
     $scope.timeOfDay = 'new day';
   };
   $scope.setAge = function(){
     $scope.display.age ='25';
   };
}]);

myApp.controller('GrandChildController', ['$scope', function($scope) {
  $scope.timeOfDay = 'evening';
  $scope.name = 'Gingerbread Baby';
}]);
})(window.angular);

This demonstration builds upon the example provided in AngularJS documentation on nested controllers.

Answer №2

It is recommended to encapsulate all templates and controllers within components, keeping them hidden from external controllers

<component1 ng-if="req1"></component1>
<component2 ng-if="req2"></component2>
<component3 ng-if="req3"></component3>

Additionally, make sure to utilize ControllerAs for proper scope management.

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 are the best ways to prioritize custom events over ng-click events?

Recently, I developed a web application using AngularJS. One of the features I included was an input text box with a custom ng-on-blur event handler. Due to some issues with ng-blur, I decided to create my own custom directive called ngOnBlur. Here's ...

Obtain the response header variable within a Shiny application

In Apache, the LDAP login is passed to a variable called X-Remote-User in the header: I am unsure how to retrieve this information in my Shiny app. Does anyone have any ideas? Maybe using JavaScript could be a solution? ...

What is the best way to connect a relative CSS stylesheet to a master page?

My Java application generates several HTML pages, organized in different directories: html_pages/ | ----> landin_page.html html_pages/details | ----> index1.html html_pages/more_details | ----> index2.html html_pages/css | ...

Obtaining the desired element from a function without relying on an event

Recently, I've been working on a sidebar with several links <sidebar-link href="/dashboard" icon="HomeIcon" :is-active="isActive()" /> <sidebar-link href="/test" icon="TestIcon" :is-active=&qu ...

unable to assign values to this.props (appears as undefined or an empty array)

Upon setting up react/redux, I encountered a peculiar issue. When my component mounts, it should render the information stored in this.props.heroes.data. However, upon logging this data, I receive an unexpected value of [{id:1,heroname:'Batman',r ...

Create a dropdown menu using a PDO query to populate the selectable options

I need to create a Select List that dynamically populates items/information from a Query. I understand the importance of updating the select list every time the database is updated, so JQuery is required for this task. Although I have limited experience wi ...

Discover the potential of JavaScript's match object and unleash its power through

In the given data source, there is a key called 'isEdit' which has a boolean value. The column value in the data source matches the keys in the tempValues. After comparison, we check if the value of 'isEdit' from the data source is true ...

Navigating with React Router using server-side routing in the web browser

I'm currently developing a web application that utilizes react on the client side and express on the server side. For routing the client pages, I've been using react-router (link). Initially, I had success using hashHistory, but now I want to ...

Asynchronous Middleware in ExpressJS Routing

I'm having trouble implementing a middleware in Express. Whenever I make a request, I end up with infinite loading times. I've searched on various platforms but couldn't find any examples that utilize an async await middleware stored in a se ...

Unable to open a modal in Angular UI after closing the initial modal

Hey there! I've been attempting to open a modal after closing the first one, but I'm encountering an issue where the second modal appears to be opened but is actually not. I'm struggling to understand what's causing this problem. Could ...

obtain the image number by extracting a portion of the text

How can I extract the image number from a string using the sub-string function? I have applied the sub-string function to the property below. It returns 3 at the end in Chrome, but it does not work properly in Mozilla. Issue : After "-->", when I check i ...

I must adjust the size of images based on the size of the viewer's screen

Hello everyone, I could really use some assistance as I am not an expert programmer but just a site admin. My issue is this: I have a website running on PHP and I want to display images to my members while keeping them within specific size limits so they ...

What distinguishes defining a function through a prototype versus as a class property?

Check out this code snippet: Apple defines its function using a prototype. Banana defines its function using a class property. var Apple = function(){} Apple.prototype.say = function(){ console.debug('HelloWorld'); } var Banana = functio ...

The never-ending cycle and memory overload that occur when using Angular's ngRoute

It seems like I may have hit a roadblock while attempting to get ng-view and ngRoute up and running. Everything appeared to be functioning correctly, but it looks like the entire process is caught in a loop. Just to provide some context, I am working with ...

"Unexpected behavior: NextAuth is failing to return defined custom scopes

I am currently working on a NextJS project that utilizes NextAuth. Initially, everything was functioning properly with the default scopes. However, my project now requires additional claims, which are listed in the supported scopes here. "scopes_supporte ...

Guide on retrieving a nested JSON array to extract a comprehensive list of values from every parameter within every object

A JSON file with various data points is available: { "success": true, "dataPoints": [{ "count_id": 4, "avg_temperature": 2817, "startTime": "00:00:00", "endTime": "00:19:59.999" }, ... I am trying to extract all the values of & ...

Struggling to display the array after adding a new item with the push method

Seeking assistance in JavaScript as a newcomer. I have written some code to print an array once a new item is added, but unfortunately, it's not displaying the array. I am puzzled as there are no errors showing up in the console either. In my code, I ...

Is there a way to programmatically close all ui-select drop down lists?

I am currently working on a directive to enable dragging functionality for angular UI $uibModal. Additionally, I want all opened dropdown lists of ui-select within the modal body to be closed when the modal is being dragged. Is there anyone familiar with ...

Sequelize makes it easy to input records into various tables simultaneously

Embarking on my first experience with Sequelize and MySQL, I am seeking guidance on inserting data into two tables with a foreign key relationship. Let's delve into the structure of the entities - bookingDescription and bookingSummary. //bookingSumma ...

Tips for resolving the UNABLE_TO_GET_ISSUER_CERT_LOCALLY issue while attempting to install Sentry using npm or curl

https://i.stack.imgur.com/G8hfZ.png curl -sL -k https://sentry.io/get-cli/ | bash Even though I've specified not to verify the certificate with -k, I'm still facing issues trying to install it. The script is supposed to automatically install sen ...