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

Node.JS using Express: Issue : encountering EADDRINUSE error due to address being already in use

Currently, I am in the process of developing a CRUD API with Node.js and Express. Everything was going smoothly until today when a new error message popped up. It appears that I can only use a TCP Port once. Whenever the server is stopped and restarted, I ...

Retrieve JSON data from an object using the Amplify Storage feature

I recently retrieved data from an object in an S3 Bucket using Amplify. export function amplify() { let key = "68a92d44-f25a-4bd8-9543-cc95369ae9a0"; return Storage.get(key + ".json", { download: true }) .then(function(result) { return ...

`Loading CSS and JS files in node.js: A step-by-step guide`

I've searched through numerous similar questions without success, so I'm reaching out for help. My folder structure looks like this: Source Code Frontend Graphs.html Graphs.css Temperature.js Server_Backend server.js I aim ...

The value remains unchanged when using Renderer2.setProperty()

I am attempting to update the value using the rendered.setproperty() method, where the value is updating the second time on a listen event These are the values that I am sending for the first time as blank in some widget <ols-giftcard-payment-widget ...

Customize Monaco Editor: Implementing Read-Only Sections

I am currently working on setting up the Monaco Editor so that specific sections of the text content are read-only. Specifically, I want the first and last lines to be read-only. See example below: public something(someArgument) { // This line is read-onl ...

Adding a property conditionally in jsx: A guide

I have a simple example of Material UI RadioGroup code that I want to display conditionally in either a row or column format. By default, it is displayed in column format. Below is the code snippet: <RadioGroup aria-label="gender" name=&q ...

Enable Class exclusively on upward scrolling on the browser

Is there a way to dynamically change the class of an element only when the user scrolls the browser page upwards? Issue Filide>> JavaScript $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll <= 100) { ...

Save the JWT token securely within a closure

Someone mentioned that the recommended way to store JWT tokens is as follows: access_token in the application memory (like closures) refresh_token in cookie entries (HttpOnly) Currently, my access_token is stored in localStorage and used for checking aut ...

How can I combine columns within a single header in ng-table?

Looking to create a table layout with headers 'a+b' above, followed by separate headers for 'a' and 'b'. Here is the desired structure: +-------------+---------------+ | headerAB | HdrC | +-------------+ ...

What is the best way to use jQuery to filter data in a table by clicking on a specific table row?

My website contains a table with player names and servers, but I want to make them clickable for filtering purposes. For instance, clicking on a player name should reload the leaderboards to show which servers that player plays on, and clicking on a server ...

Unable to locate the root element for mounting the component in Cypress with React

I am currently testing my react app, which was created using create-react-app, with the help of cypress. Unfortunately, I encountered an error that looks like this: https://i.stack.imgur.com/xlwbo.png The error seems to be related to trying to fetch an ...

Tips for dynamically updating an input within a shadow DOM using code?

Snippet: https://jsfiddle.net/5zrwdjy7/2/ I'm currently working on automating keystrokes with a script within Cypress, however, the target website I am dealing with utilizes web components as inputs. These input elements are nested inside what is kno ...

Retrieve and manipulate custom headers from a webview within an AngularJS app

I have implemented an angular application within a webview using the following code: WebView.loadUrl(String url, Map<String, String> additionalHttpHeaders) In order to manage the content and display it appropriately, I am maintaining a state in my ...

Capybara testing integration for input fields using 'TextAngular' feature

Utilizing TextAngular for a sophisticated text input box within an AngularJS/ Rails setup. Conducting integration tests with Capybara/Selenium & Capybara-Webkit. Attempted to create a test that enters text into the text area, but have faced challenges in ...

What is the most effective way to transmit a conditional operator via a TypeScript boolean field?

Currently, as part of my transition to typescript, I am working on incorporating a conditional operator into the table component provided by Ant Design. const paginationLogic = props.data.length <= 10 ? false : true return ( <> ...

Create a system where three arrays are interconnected, with the first array representing the name of the object

I have a group of different objects structured like this: let object1 = { xyz: 'xyz1', arr: [] }, object2 = { xyz: 'xyz2', arr: [] }, object3 = { xyz: 'xyz3', arr: [] } Manag ...

Run the command "node index.js" to simultaneously start and stop the server

After installing WSL2 and the Ubuntu 22.04 distribution on Windows 11, I set up my environment, installed nvm, Node version 16.17.1, and then ran npm init in my folder. Following that, I installed Express and created an index.js file with a simple structur ...

JavaScript Promise Handling: using fetch method to retrieve and extract the PromiseValue

I am currently struggling to access the [[PromiseValue]] of a Promise. However, my function is returning a Promise instead and what I really want myFunction to return is the value stored in [[PromiseValue]] of the promised returned. The current situation ...

There was a parsing error due to an unexpected token, and we were expecting a comma instead

Below is the code snippet written in react js: class Posts extends Component { render() { return ( {console.log('test')} ); } } When I executed this code, an error occurred stating: Parsing error: Unexpected token, expected " ...

Submit a list of checkboxes selected to Google Sheets separated by commas

Is there a way to modify the script I'm using to enter data from an HTML form into a Google Sheet so that my checkbox fields will be entered as a list, separated by commas? If all boxes were checked in the example form below, I would like the cell fo ...