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

"Efficiently fetch data with an Express GET request without the

My goal is to send the client the HTML page (create.html) in response to a GET request triggered by a button click using fetch. I am intentionally avoiding the use of a form due to formatting and potential scalability issues. The code acknowledges that the ...

Adjust the height of each child element to be half of the fixed height of the parent

There is a wrapper containing multiple boxes generated using ng-repeat from a list. The wrapper has a fixed height of 300px. If the list contains only one box, a class is added to fill the entire space of the wrapper. However, when there are more than on ...

Playing with background hues

Can anyone help me with this issue? I've been attempting to change the background color using jQuery upon document load, but it doesn't seem to be working. Any thoughts on what I might be doing wrong? http://jsfiddle.net/KczZd/2/ HTML: <d ...

Leveraging jQuery's Append functionality

Struggling with using jQuery's .append() method. Check out my code: $('#all ul li').each(function() { if ($(this).children('.material-icons').hasClass('offline-icon') == false) { $('#online ul').append ...

Organizing your code with precision

I'm struggling with a project due to the poorly formatted code, making it almost impossible to read. Despite my attempts with various plugins and tools in VIM, Netbeans, Sublime Text 2, and Eclipse, the situation only seems to worsen. If anyone has ...

Implement a Selection Feature in Angular

Currently, I am working on an application where users can add new rows with the same fields. One of the requirements is to allow users to add an option to a select element. While I have successfully implemented this in jQuery, I am facing challenges integr ...

How can I effectively refresh the provider_token / access token for Discord in NextJS with Supabase Auth?

Currently, I have encountered an issue with my NextJs project using Supabase Auth for authentication. I am currently utilizing the Discord provider and everything works fine initially. However, after a few minutes, the session object gets updated and the p ...

Mobile Chrome allows users to utilize the IFrame player API for enhanced video

Currently, I am working on creating a mobile website where I plan to include some YouTube videos using the IFrame player API (https://developers.google.com/youtube/iframe_api_reference). My main goal is to have the video start playing only after the user ...

Enhanced Rating System for Asp.Net

How can I retrieve the selected value (CurrentValue) of the ASP.NET Rating control in javascript? I have it implemented within a datagrid, and I am facing difficulty in accessing the CurrentValue property. Any suggestions or solutions for this issue woul ...

converting a JSON object into an array

I'm facing a challenge and unsure how to proceed. I have received JSON data from an API: https://i.stack.imgur.com/GdDUo.png When I log the data, this is what appears in the console: https://i.stack.imgur.com/GjSPW.png My goal is to extract the id ...

What is the process for invoking a server-side Java function from HTML with JavaScript?

Can someone help me figure out the best way to invoke a Java method from HTML (I'm working with HTML5) using JavaScript? I attempted using Applets but that approach didn't yield any results. My goal is to extract the value from a drop-down menu i ...

Instructions for adding an onfocus event listener to an input field in order to dynamically change the formatting of associated labels

I'm looking to change the style of my input labels to a more fancy look by implementing the .fancyclass style when using the onfocus event on the input field. I am curious to know how this can be achieved through event listeners in Javascript? ...

Is there a module loader in Angular.JS or do I have to rely on script tags for loading modules?

While using Angular JS, I have a desire to organize unrelated code in separate modules similar to AMD or CommonJS. However, my Google search for 'Angular.JS make new module' has not yielded any documentation on creating Angular.JS modules. There ...

Is it the same item in one situation, but a completely different item in another?

I am currently investigating the behavior of objects in JavaScript, particularly when it comes to copying one object onto another. It seems that sometimes they behave as if they are the same object, where modifying one also modifies the other. Many resourc ...

How can I access the parent function within module.exports?

Hello, I am having issues with this code because I am unable to access checkIf in order to set its property LengthIs. When I log whether this is equal to module.exports, it returns false. Upon further inspection, I also checked what this was and it retur ...

Encountering issues accessing the key value 'templateUrl' in Angular6

I have an object in my component.ts file that I need to iterate through in the HTML template using a ui-comp-menu element. menuObject = [{ 'labels': 'Content1', 'templateUrl': 'assets/partials/sample.html ...

Looking for a way to make this HTML tab appear using ng-show and an external variable in AngularJS - seeking guidance as a beginner!

Here is the HTML code snippet controlling the tab presentation: <li class="presentation" ng-show="currentUserAuthority == LIBRARIAN" > However, there seems to be an issue with the variable "currentUserAuthority" not updating until after the web pag ...

Experience an issue in your Ionic/Angular app with the `e.gesture` being undefined during Drag & Drop functionality. Additionally, explore the use of two separate Controllers

Currently, I am in the process of developing an application that requires the implementation of Drag & Drop functionality as a primary interaction feature. To provide a clearer picture, envision an Ionic Side Menu containing an <ion-list> displaying ...

Send back alternate HTML content if the request is not made via AJAX

Last time I asked this question, I received several negative responses. This time, I will try to be more clear. Here is the structure of a website: Mainpage (Containing all resources and scripts) All Other pages (HTML only consists of elements of that ...

Unable to create selected buttons in Vue.js

I'm having trouble creating buttons that can select all options when clicking on either size or color. The buttons aren't showing up at all. Can someone help me identify the issue? I've attempted various solutions but none seem to work. Any ...