The AngularJS Navbar is Bootstrapped

I'm currently working on a project where I need to make a bootstrap navbar show and hide html elements based on data retrieved from an angular controller.

Below is the jade code snippet:

div.navbar.navbar-fixed-top
    div.navbar-inner
        div.container-fluid(data-ng-controller="NavCtrl")

            a.btn.btn-navbar(data-toggle='collapse', data-target='.nav-collapse')
                span.icon-bar
                span.icon-bar
                span.icon-bar

            div.nav-collapse.collapse
                ul.nav
                    li  
                        a(href='/topics') Topics
                    li(ng-show="curUser.admin")
                        a(href='/users') Users
                    li(ng-show="curUser.admin")
                        a(href='/organizations') Organizations
                    li(ng-show="curUser.admin")
                        a(href='/topicConfs') TopicConfig
                    li.divider
                ul.nav.pull-right
                    {{authenticated}}
                    li.dropdown(ng-show="authenticated")
                        a.dropdown-toggle(role='button', data-toggle='dropdown', href='#') {{curUser.email}}
                            b.caret
                        ul.dropdown-menu(role='menu')
                            li
                                a(href='/users/{{curUser._id}}') Profile
                            li.divider
                            li
                                a.btn(ng-click="logout()") Logout 

Along with a controller that looks like this:

function NavCtrl($location, $scope, $rootScope, CurrentUser){
  $scope.curUser = CurrentUser.getUser()
  $scope.authenticated = CurrentUser.isAuthenticated()

  $rootScope.$on('$routeChangeStart', function(){
    $scope.curUser = CurrentUser.getUser()
    $scope.authenticated = CurrentUser.isAuthenticated()
  })


  $scope.logout = function(){
    CurrentUser.logout(function(result){
      $scope.curUser = CurrentUser.getUser()
      $scope.authenticated = CurrentUser.isAuthenticated()
      console.log("authenticated before logout is %j", $scope.authenticated)

      $location.url('/')
    })
  }
}

Everything works fine until $scope.authenticated is set to false and $scope.user is set to {}, at which point the ng-show attributes in the nav-bar do not update as expected.

How can I ensure that the bootstrap nav elements respond correctly to changes in the $scope variables?

Answer №1

When properties in the Angular $scope are modified externally, it is necessary to invoke $scope.$apply() in order to trigger Angular to run its digest loop. This loop will then evaluate any properties that are displayed on the current view. Once a change is detected in one of these properties, the view is automatically updated.

Situations where modifications occur externally:

  • Browser event callback. Example:
    element.bind('someEvent', function() {

       // calling scope.$apply here
    })
  • Callback from a third-party plugin. For instance, the callback provided for logout.
  • AJAX callback from a third-party source.
  • Promise from a third-party library.

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 a Javascript function through Typescript in an Ionic application

I integrated a plugin into my ionic project, which includes both Java and JS code: cordova.define("cordova-sms-plugin.Sms", function(require, exports, module) { 'use strict'; var exec = require('cordova/exec'); var sms = {}; functio ...

Using Javascript to efficiently remove elements with AJAX

Currently, I am learning the basics of HTML and focusing on tasks such as login/logout functionality, creating users, and deleting users (only permitted when logged in as an admin). For updating a user password, I have utilized PUT, for creating a user ac ...

Tips on storing chosen language in local storage or cookies using AngularJS

As a newcomer to angularjs, I am facing the challenge of saving the selected language from a dropdown menu in HTML to either local storage or cookies. This way, when a user navigates to another page, the language they previously chose will be loaded and us ...

Sending various data from dialog box in Angular 8

I have implemented a Material Design dialog using Angular. The initial example had only one field connected to a single parameter in the parent view. I am now trying to create a more complex dialog that collects multiple parameters and sends them back to t ...

Deactivate debugging data for Tensorflow JS

Is there a way to turn off all debugging logs in Tensorflow JS similar to what can be done in Python with setting an environment variable and calling a function? Disable Debugging in Tensorflow (Python) According to the top answer: import os os.environ[ ...

Combine table cells to improve readability on smaller screens

I currently have a setup designed for larger screens: <table> <thead> <tr> <th>title and image</th> <th>description</th> </tr> </thead> <tbody> ...

A guide on using Javascript to write information to a JSON file

Let's consider an example where we have a .JSON file with the following content: [{"honda": "accord", "color": "red"},{"ford": "focus", "color": "black"}] We are looking to add another object {"nissan": "sentra", "color": "green"} into this existing ...

Tips for enabling simultaneous input focus on both TextField and Popover components

I am working on a popover component that appears below a textfield component. The goal is to trigger a menu when the user types a specific key, like :, into the textfield. The user can then select an option from this menu to autocomplete the textfield. A ...

Is there a similar function in AngularJS that is equivalent to getJSON? Just curious, as I am new to this

As a beginner in javascript, angularJS, and JQuery, I recently embarked on programming an angularJS app that involves using JQuery to fetch JSON data from a webserver. Here is the code snippet I am working with: var obj = $.getJSON( "http://something.com/ ...

Detecting collisions in JavaScript

Currently, I am in the process of reviving an old game reminiscent of Tron using HTML5 canvas and JavaScript. The unique twist in this version is that the snakes have the ability to move in curves rather than right angles (known as Achtung Die Kurve). The ...

Exploring Interactive Designs with Vue.js

In order to dynamically construct a series of CSS style classes based on the toolName property in the JSON data using Vue 2, I tried to use a computed property to bind them to the existing span with a class of panel-icon. However, when attempting to save t ...

Filtering in AngularJs with multiple select options

I am curious about how to create a filter with multiple options. I have a grid with specific settings and column definitions as shown below: $scope.gridOptions = { enableHorizontalScrollbar: 1, enableFiltering: true, p ...

Using values from a select menu in a math calculation without including a decimal point

I am working with a dropdown menu that contains various values... <select id="number1a" onChange="Addition()"> <option value="0" selected>-</option> <option value="10">10</option> <option value="7.5">7.5</optio ...

Ways to identify when the scroll bar reaches the end of the modal dialog box

I have been working on a modal that should display an alert when the scrollbar reaches the bottom. Despite my efforts to research a solution, I am struggling to detect this specific event within the modal. The desired outcome is for an alert to pop up once ...

Sending multiple ajax requests with identical data

I have been trying to send multiple requests to the same URL. The goal is to ban all the users that are included in the 'users' array by sending individual POST requests for each user. However, I am facing an issue where I keep getting the same d ...

Implementing a Countdown Clock in Auction Listings

Similar Question: Countdown to a specific date Is there a way to implement a jQuery countdown timer that starts from the day of posting an advertisement and ends on the expiry date? ...

Apply SetTimeout exclusively for desktop devices

A website I'm working on has a background video from YouTube using YTPlayer. To enhance the user experience, I have implemented a CSS spinner that displays while the page is loading. However, I noticed that the spinner disappears before the video fini ...

Navigate to the end of the progress bar once finished

I have a solution that works, but it's not very aesthetically pleasing. Here is the idea: Display a progress bar before making an ajax call Move the progress bar to the end once the call is complete (or fails) Keep the progress bar at 90% if the aj ...

Button to scroll down

I have successfully implemented a #scrolldownbutton that scrolls to the first component. However, I am now attempting to modify it so that when the button is clicked, the page smoothly scrolls within the viewport and stops at the partially visible componen ...

Sending the most recent result to each dynamically created div

In my WordPress project, I have an event panel that displays upcoming event details and shows the remaining time until the next event. The countdown dynamically gets values from the database and calculates the time left based on the user's input in th ...