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

Executing an Angular 4 script using a scheduled CRON job

We are currently facing a challenge with our Angular-built APP for Android phones. The logic has become quite intricate and we have decided to transfer it to our server, where it can be executed as a CRON job every hour instead of within the Phone APP it ...

Having difficulties updating a value in Angular through a function written in HTML- it refuses to update

<select ng-model="currentTimeStartHour" style="width: 33%" ng-change="UpdateTime(this)"> <option ng-repeat="hour in choices" value="{{hour.id}}">{{hour.name}}</option> </select> Somewhere else on the page... {{totalHours}} Whe ...

Is using selectors a more effective way to retrieve computed data compared to using class methods?

When using react, redux, and reselect in a project, is it preferable to move all computable data from class methods to selectors and avoid mixing the use of both? Are there different concepts behind these approaches? class DocsListView { getOutdatedDocs ...

What is the best way to retrieve a nested element from a JSON object using AngularJS?

Take a look at this Plunkr demonstration that showcases the ng-repeat functionality with a JSON file: Plunkr The code snippet below shows how I am displaying elements from $scope.foodlist: <li ng-repeat="food in foodlist"> ...

Are there any extensions in VS Code that can identify all files that are importing the current file?

class ButtonNoclickTag is exported default {...} I am curious to find out which files have imported this ButtonNoClickTag component through vscode ...

What is the best way to generate a fresh JSON object within a react hook function?

I am currently facing two issues. Firstly, I am having trouble figuring out how to add/update the JSON items within a hook. Secondly, React seems to be restricting me from using the name that is stored in a previous JSON file. I am open to exploring alter ...

What causes this statement to consistently be incorrect?

I am in the process of developing a Q&A platform where users can vote on answers. I have assigned project.problem.upVoted to store a list of answers that the user has already upvoted. If an answer has already been voted on, the callback function for cl ...

jQuery condition doesn't properly resetting the states of the original checkboxes

Having trouble phrasing the question, apologies! Take a look at this fiddle to see my objective: http://jsfiddle.net/SzQwh/. Essentially, when a user checks checkboxes, they should add up to 45 and the remaining checkboxes should then be disabled. The pr ...

Toggle the visibility of an element using a checkbox in JavaScript

In my scenario, there are 8 checkboxes where only one is checked by default. If you click on the unchecked checkboxes twice, the table linked to them will hide. Ideally, I want the unchecked checkboxes to be hidden by default and the checked one to be sh ...

Tips for configuring jQtree to initially display the tree structure from the HTML source

Up to this point, I have utilized jQuery TreeView for the navigation menus on my website. However, as the main navigation menu has grown significantly in size (40869 bytes out of 67054 bytes), I am seeking a way to streamline it by using AJAX calls to fetc ...

Activate the stripe button after successful bootstrap validation

My goal was to implement BootstrapValidator for validation on a couple of fields and enable the Stripe button only when both fields are valid. Currently, the button is enabled once any of the fields pass validation. The challenge lies in ensuring that the ...

Are multiple .then(..) clauses in Javascript promises better than just using one .then(..) clause?

In this particular scenario, I have set up a basic 'toy' node.js server that responds with the following JSON object: { "message" : "hello there" } This response is triggered by making a GET request to "http://localhost:3060/" So, it's reall ...

How can I modify my for loop with if else statements so that it doesn't just return the result of the last iteration in

Today is my first day learning JavaScript, and I have been researching closures online. However, I am struggling to understand how to use closures in the code I have written: function writeit() { var tbox = document.getElementById('a_tbox'). ...

jQuery fails to locate class following AJAX reply

In my application, there is a cart feature where users can remove items from their cart, triggering a refresh of the contents using AJAX. However, I noticed that after removing an item from the cart, the response switches from asynchronous to synchronous m ...

Top method for organizing an array based on an object's property and displaying the outcome

I encountered a problem for which I couldn't find an immediate solution. I have an array of objects representing products, with each product having a category property. My goal is to group these products by their categories. After some trial and error ...

Obtain information from the get request route in Node.js

I've been diving into nodejs and databases with the help of an online resource. As part of my learning process, I have been tasked with replicating the code below to fetch data from app.use('/server/profil'); However, I'm encountering ...

When state is updated, the component is re-rendered multiple times

I am working on setting the state in componentDidMount lifecycle method to verify data from local storage. Depending on whether the data exists in local storage, I either redirect the user to the login page or keep them on the dashboard. Is there a way to ...

The class 'ConsoleTVsChartsCharts' could not be located

Attempting to implement Laravel charts using the package consoletvs/charts:6.*, Utilizing service providers ConsoleTVs\Charts\ChartsServiceProvider::class, With an alias: 'Charts' => ConsoleTVs\Charts\Charts::class, ...

Align the camera to be perpendicular with the ground

Ensuring that my fly camera always remains parallel to the ground is crucial to me. Specifically, I need my camera's right vector to always be (1,0,0). To achieve this, I have developed a customized Camera Controller in three.js that simulates unique ...

Problem with the content-editable attribute

My goal is to make each div with the class .edit editable by adding the contenteditable property: $(document).ready(function() { $(".edit").attr("contenteditable", "true"); }); However, after applying this, I found that clicking on a div with content ...