Executing the AngularJS nested controller only once

I am still new to Angularjs and just started working on an app that has several "projects" each with a local menu displayed on specific pages. The main navbar with footer is located in the Index.html:

<body ng-app="ysi-app" ng-controller="MainController">
<div class="page-content">
<div class="row">
    <div class="col-md-2">
        <div class="sidebar content-box" style="display: block;">
            <ul class="nav">
                <!-- Main menu -->
                <li ng-if="isAuthenticated()"><a href="#/">{{name}}</a></li>
                <li class="current"><a href="index.html">Dashboard</a></li>
                <li><a href="#/project">Projects</a></li>
            </ul>
        </div>
        <div ng-if="isAuthenticated() && displayProjectMenu == true" ng-include="'views/localMenu.html'" ng-controller="LocalMenuController">
        </div>
    </div>
    <div ng-view></div>
 </div>

There is a nested controller called LocalMenuController for handling the local menu and a main controller. The project controller sets the data as follows:

angular.module('ProjectCtrl',[]).controller('ProjectController',function($scope,$location, ProjectService,$route, AuthenticationService, $rootScope){

    $scope.setProjectDatas = function(projectName, projectId){
        ProjectService.setName(projectName);
        $rootScope.projectId = projectId;
    };});

To ensure proper testing, I temporarily set the id of one project to the $rootScope, which can be accessed in the LocalMenuController:

angular.module('LocalMenuCtrl',[]).controller('LocalMenuController', function($scope, ProjectService, $rootScope) {
    $scope.projectId = '';
    $scope.projectId = $rootScope.projectId;
});

When displaying projects in a table, clicking on a particular project triggers the setProjectDatas(name,id) function. However, there seems to be an issue where the id of the previous project clicked remains when clicking on a new project. It appears that the data is not updating properly. Despite searching for solutions online, no relevant information was found.
It seems like the LocalMenuController is only being called once and not again.

Can anyone help me understand what may be going wrong here?

Thank you

UPDATE
I attempted to address this by creating a Directive, but it still does not update the partial view localMenu. LocalMenu Directive:

angular.module('LocalMenuCtrl',[]).controller('LocalMenuController', function($scope, ProjectService, $rootScope) {
    console.log('-> LocalMenu controller');
})
    .directive('localMenu', function($rootScope){
        return {
            templateUrl: '/YSI-Dev/public/views/partials/localMenu.html',
            link: function(scope){
                scope.projectId = $rootScope.projectId;
            }
        };
    });

A snippet from index.html

<div ng-if="isAuthenticated() && displayProjectMenu == true" ng-controller="LocalMenuController">
                <div local-menu></div>
            </div>

The content of Partial view localMenu :

<div class="sidebar content-box" style="display: block;">
    <ul class="nav">
        <li><a href="#/project/{{projectId}}"><i class="glyphicon glyphicon-list-alt"></i> Backlog</a></li>
        <li><a href="#/project/{{projectId}}/members"><i class="glyphicon glyphicon-user"></i> My team </a></li>
    </ul>
</div>

I am trying to retrieve the projectId from the $rootScope and insert it into the

<a href="#/project/{{projectId}}"
tag, but encountering challenges. Can someone guide me on the correct approach to achieve this?

Answer №1

To enhance your code, consider implementing directives in place of ng-controller. By encapsulating your code and template into a single unit, you can achieve better organization. Another option is to explore creating components, allowing for data to be passed to them. Angular will handle the updates to the template and execution within the directive or component if two-way data-bindings are utilized.

Upon reviewing the given code, it is unclear what would prompt LocalMenuController to run again.

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 locate and access a JSON file that is relative to the module I am currently working

I am in the process of creating a package named PackageA, which includes a function called parseJson. This function is designed to accept a file path pointing to a JSON file that needs to be parsed. Now, in another package - PackageB, I would like to invok ...

Position divs to be perfectly aligned and centered

I'm in the process of creating a webpage and facing challenges with aligning my divs properly, specifically the animated company logos. I want them to be positioned side by side rather than on top of each other, with space in between to fit the layou ...

Step by step guide on adding content to a div by clicking a button, even after the page has already loaded

I have scoured the depths of the internet and forums but have yet to find a satisfactory solution to my problem. Hopefully, someone reading this can offer some help in resolving my issue. I manage a website that showcases concerts for various music groups. ...

Performing two simultaneous AJAX requests using tokeninput

I've been playing around with the tokeninput plugin and it's been working really well for me. However, I recently came across a new requirement - I need to make two separate ajax calls on the same input bar. Situation: My input bar is as follows ...

Mastering the Art of Resizing Video Controls: A

https://i.stack.imgur.com/jTgap.png https://i.stack.imgur.com/Exf6Y.png On the initial screenshot, the video player displays normal controls. However, on the same website with identical CSS, the second video player shows different control settings. // C ...

Click on a new tab to enable printing options for the page

I am looking to enhance the print page functionality on my website. Currently, when the print icon in the footer is clicked, it opens the printer dialog box directly. I would like to change this behavior so that when the Print icon is clicked, the contents ...

Guide to configuring the initial lookAt/target for a Control

I'm looking to establish the initial 'lookAt' point for my scene, which will serve as both the center of the screen and the rotation control's focus. Ideally, I'd like to set a specific point or object position rather than rotation ...

How can we showcase an HTML file in Express by utilizing a POST request?

My objective is to successfully submit my form data and then dynamically navigate to an HTML file where the values are displayed. Here's the code snippet from my app.post function in Express: const results = fs.readFile("order.html", " ...

While running tests on a React project, the `npm test` command is successful, but unfortunately,

I created a new react app using create-react-app and included some basic components and tests. The tests work fine when running 'npm test', but I encounter an 'Unexpected token' error when using Jest to run the tests with imported compo ...

Having trouble with my ASP.Net OnClick Subs not functioning as desired

I have implemented onClick handlers to process button clicks that query SQL. The issue I am facing is that these queries sometimes take between 10 to 30 seconds to return a response. To prevent click-stacking during this time, I disabled the buttons. Howev ...

Deciphering JSON information extracted from a document

I am currently working on a Node JS project where I need to read a file containing an array of JSON objects and display it in a table. My goal is to parse the JSON data from the array. Below is a sample of the JSON data: [{"name":"Ken", "Age":"25"},{"name" ...

Asynchronous task within an if statement

After pressing a button, it triggers the check function, which then executes the isReady() function to perform operations and determine its truth value. During the evaluation process, the isReady() method may actually return false, yet display "Success" i ...

Is there a way to position two Grid elements to the left and one to the right in Material UI, especially if the first Grid element has a specified width

I'm currently using Material UI and have a Grid layout with three items. The left item needs to have a fixed width of 240px and be aligned to the left. The middle item should be left justified and can have any width, containing buttons that I've ...

Find all relevant employee information at once without the need for iteration

I have structured two JSON arrays for employee personal and company details. By inputting a value in the field, I compare both tables and present the corresponding employees' personal and company information in a unified table. <html> ...

Is there a way to generate random numbers that will create a chart with a general upward trend?

Are you looking for a solution to generate random numbers for charts that trend upwards and to the right? I am currently utilizing a JavaScript charting engine, so I will require numbers in JSON format eventually. However, I am open to alternative methods ...

Showcase your skills in CSS, HTML, and Javascript

I attempted to search for something similar but came up empty-handed. I have two buttons. When I click one of them, I want to hide a certain division, but it's not working as expected. The divs d2 and d3 are initially hidden when the page opens, whic ...

Utilizing Regular Expressions in Sails.js Routing

Currently, I am working on a sails.js project and utilizing backbone for the front end. My goal is to have a single route leading to the index page where my backbone application is hosted. '/*': { view: 'home/index' } This setup ...

Console.log is displaying array as [object Object] when utilizing Typescript

When working with an object in typescript called "obj," I encountered a strange behavior. Initially, when I ran the console.log(obj); command, the output in the terminal console was displayed as [object Object]. However, after wrapping it in JSON.stringify ...

Can you explain the purpose of useEffect in React?

As a beginner in learning React, I have been able to grasp the concept of the useState hook quite well. However, I am facing some difficulties understanding the useEffect hook. I have tried looking through the documentation, searching online, and even wat ...

Await the sorting of intervals

Looking for a solution to re-execute a hand-made for loop with a delay of 10 seconds after it finishes indefinitely. I've attempted some code, but it keeps re-executing every 10 seconds rather than waiting for the loop to finish before starting again. ...