Adjust the ng-show attribute in a different controller

I am attempting to toggle the visibility of a div using ng-show. Specifically, I have a navbar that should only be displayed in certain views.

I have one controller managing the behavior of this div, and another controller where I want to manipulate the value of ng-show to show or hide the navbar.

I've experimented with various approaches such as using $rootScope, timeouts, $apply, factories, but so far nothing has been successful.

Any assistance would be greatly appreciated.

(Apologies for any language errors)

Below are snippets of my HTML and JS code:

<div id="main">
    <!-- Injecting views here -->
        <div ng-controller="appCtrl" ng-show="isLogged" class="navbar navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button>
                    <a class="navbar-brand" href="#/">Aula Virtual</a> </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav" style="text-align: right">
                        <li class="active"><a href="#/home">Home</a></li>
                        <li><a href="#/server">Users</a></li>
                        <li><a href="#/operaciones">Operaciones</a></li>
                        <li><a href="#/about">About</a></li>
                        <li><a href="#/contact">Contact</a></li>
                    </ul>
                </div>
            </div>
            <div class="connect">
                <div class="container">
                    <p>
                        Aula Virtual for university professors and students
                    </p>
                </div>
            </div>
        </div>
    <div ui-view></div>
    </div>

I also attempted using (ng-show="isLogged==false").

The controller for the div:

.controller('appCtrl', function($scope, $rootScope) {
        console.log($scope.isLogged); // displays undefined
    });

The controller where I aim to modify the isLogged value:

cities2.controller('userCtrl',['rootScope', '$scope', '$state','$http','md5', function($rootScope, $scope, $state, $http, md5) {
    $rootScope.$apply(function(){
        $rootScope.isLogged = true;
    });

Thank you for your assistance!

Answer №1

Sharing data between controllers using services is a recommended practice.

cities2.controller('appCtrl', ['$scope', 'SessionState', function($scope, SessionState) {
    $scope.SessionState = SessionState;
}]);

cities2.controller('userCtrl', ['$scope', 'SessionState', function($scope, SessionState) {
    $scope.SessionState = SessionState;
}]);

cities2.service('SessionState', function() {
  return {
    isLoggedIn: false
  }
});

Any changes to $scope.SessionState.isLoggedIn in one controller will reflect in both controllers.

Answer №2

To make a block visible in your appCtrl controller, set $scope.isLogged=0. Changing this value to 1 will show the block, otherwise it will be hidden.

app.controller('appCtrl', function($scope) {
  $scope.isLogged=0;
})

Check out the plunker link for reference:

https://plnkr.co/edit/d3q3QwA9k5f6ewXbqZ3M?p=preview

Answer №3

After some time searching, I finally discovered the solution. Here's what worked for me:

I added a .run function to my appCtrl where I initialized the ng-show variable:

.run(function ($rootScope) {
        $rootScope.isUserLoggedIn = false;
    });

Now, when I set the value to true in another controller, the navbar appears as expected.

cities2.controller('userCtrl',['$rootScope', '$scope', '$state','$http','md5','$sessionStorage',  function($rootScope, $scope, $state, $http, md5, $sessionStorage) {
    $rootScope.isUserLoggedIn = true;
  }]);

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

The color input click event does not work properly when triggered within a context menu event

This may sound a bit complicated, but let me try to explain it clearly. I'm working on a web app where I want users to be able to change the background color of certain divs. I plan to use a color picker interface for this purpose and utilize the con ...

Unable to process JavaScript function

Still in the process of developing my "mvc/social" PHP project, I am currently focusing on securing user input for the status message. I have created both a PHP and JavaScript function for this purpose, but it seems like the JavaScript function is not bein ...

Maximizing React Performance: Strategies for Avoiding Unnecessary Renderings on State Updates

I am facing a major performance issue due to constant re-rendering of my child components on every state change. I need a solution to prevent this from happening and maintain the stability of my application. Any suggestions or guidance would be highly ap ...

Angular component not transmitting any data through binding

I have a page with two components. Component A is named Dashboard, which displays a list of elements using ng-repeat. These elements, referred to as systems, are shown through Component B called SystemView. Each SystemView contains a list of log entries, a ...

Can a snapshot be taken of an auto-generated ID document in FireStore?

Currently, I am working on developing both a mobile app and web app for my Final Year Project. As someone relatively new to Firestore, I am using a single instance of it to store data. When a customer registers through the mobile app, their information ge ...

Why does the request for server parameter 'occupation=01%02' function correctly, while 'occupation=01%2C02' or 'occupation=01&occupation=02' result in an error?

There seems to be an issue with the parameter when using the API to request data from the server. The value 'occupation=01%02' works correctly when entered directly into the browser URL, but errors occur when using 'occupation=01%2C02' ...

Exploring the process of retrieving outcomes from Node.js within a Knockout ObservableArray

Below is the Node.js code snippet I have: var http = require('http'); var port = process.env.port || 1337; var MovieDB = require('moviedb')('API KEY'); MovieDB.searchMovie({ query: 'Alien' }, function (err, res) { ...

How to utilize dot notation in HTML to iterate through nested JSON in AngularJS?

I'm struggling with displaying nested objects loaded from a JSON file in Angular. I've seen examples of using dot notations in HTML to access nested data, but I'm new to Angular and can't seem to get it right. The JSON is valid, but I j ...

The Vue.js input for checkboxes and radios fails to toggle when both :checked and @input or @click are used simultaneously

Check out this example on JSFiddle! <script src="https://unpkg.com/vue"></script> <div id="app"> <label> <input type="checkbox" name="demo" :checked="isChecked" @input=" ...

Tips for utilizing a ForEach loop in JavaScript to create an object with dynamically provided keys and values

Looking to create a JavaScript object with the following structure, where the Car Make and Model Names are provided from other variables. { "Sedan":{ "Jaguar":[ "XF", "XJ" ], "AUDI":[ "A6", ...

When hovering over a select option, a description and clickable link will be displayed

I need to display a description with a clickable link when hovering over any option in the select tag. <div class="col-lg-4"> <div class="form-group"> <label class="form-label">Goal</label> <select name="semiTaskType ...

Verify authentication on a SignalR console application using a JavaScript client

Here is the scenario and solution I am currently working on: In project one, I have a SignalR console application that handles the logic, including authentication using Entity Framework to query the database. In project two, I have an ASP.Net web applicat ...

Exploring the Versatility of Axios

Today, I implemented an AJAX request using Axios in JavaScript to submit form data. While the requests are being sent successfully, it seems that the backend is not able to receive the username and password information from the frontend. What could be ca ...

Creating a standard login.js file for seamless integration with nightwatch.js testing

When creating tests for my web application, I need to first simulate a login before proceeding with the rest of the tests to access inner pages. Currently, I am in the process of refactoring the code so that I can create an 'include' for common f ...

What might be causing the value to become undefined when attempting to push key-value pairs into the $scope object again?

My problem is while attempting to append the comment to the $scope.comments array. All key-value pairs are getting added to $scope.comments except for the initial key, which needs to be shortened using capitaliseUsername(comment.owner). $scope.comments.pu ...

The Chrome extension functions properly when the page is refreshed or loaded, but it does not work with internal navigation

When landing on a YouTube page starting with w*, I have a script that triggers an alert with the URL. However, this only works when entering the page directly or upon refreshing. I am trying to make the alert trigger when navigating internally to that page ...

Issue: "StoreController Undefined" error in Python Flask + Angular application

In the python flask application that I have built with Angular JS for the front end, there are three main files. app.py import json import flask import numpy as np app = flask.Flask(__name__) @app.route("/") def index(): ...

Discover the process of integrating PWA features into an Express web application

I'm currently in the process of integrating PWA into a web application. I've created a manifest.json file and added it to the head of my page, which is loading correctly. However, the service worker registered in my app.js doesn't seem to be ...

The pagination feature in ui-bootstrap-tpls 1.0.0 or later versions is not showing up as expected

I am currently using the "pagination" directive from ui-bootstrap-tpls <pagination total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()"></pagination> If you want to see a plunker Demo of version 0.14.3 of ui-bootstrap-tpl ...

Leveraging global attributes beyond Vue components - Vue 3

I have created custom service instances in main.ts app.config.globalProperties.$service1 = new Service1(); app.config.globalProperties.$service2 = new Service2(); While I can use these instances inside Vue components, I also want to be able to utilize the ...