Unable to set the active tab using $rootScope

Is there anyone who can assist me with the issue I am currently facing? I have a NavCtrl to manage my active tags, and although I was able to change the active tab when clicking on the menu item, it does not update when clicking on links in the body views.

//controller for navigation menu
sp.controller('NavCtrl', ['$scope', 'auth', '$window','$rootScope', function ($scope, auth, $window,$rootScope) {
    $scope.LogOut = auth.logOut;
    $scope.isLoggedIn = auth.isLoggedIn;
    $scope.tab = $rootScope.navTav;

    $scope.toTop = function(){
        $window.scrollTo(0, 0);
    };
}]);

I attempted to use $rootScope to set the navTab, but unfortunately, it did not resolve the issue.

//setting root scope
sp.run(function($rootScope) {
    $rootScope.navTav = 1;
})

ui-Router

.state('qaanswer', {
    url: '/qa/{quesId}',
    views: {
        view50': {
            templateUrl: './qa/qaanswer.html',
            controller: 'QAAnswerCtrl'
        },
        'view60': {
            templateUrl: './shareviews/activityupdates.html',
            controller: 'HomeCtrl'
        }
    },
    onEnter:['$rootScope',function($rootScope){
        $rootScope.navTav = 5;
    }]

I appreciate any assistance provided. Thank you.

Answer №1

Latest HTML Update:

  <body ng-controller="NavCtrl">
    <!-- Desktop Menu Section -->
    <div>
      <div>
        <ul>
          <a href="#/about" ng-class="{active: navTab === 1}" ng-click="navTab = 1">
            <li>About</li>
          </a>
          <a href="#/contact" ng-class="{active: navTab === 2}" ng-click="navTab = 2">
            <li>Contact</li>
          </a>
        </ul>
      </div>
    </div>
    <div>
      <div>
        <div class="row">
          <div ui-view="view50"></div>
          <div ui-view="view60"></div>
        </div>
      </div>
    </div>
  </body>

Clickable plunker

Answer №2

To simplify your implementation and prevent any issues, consider using the $rootScope variable directly in your template with ng-class:

<body ng-controller="NavCtrl">
    <a ng-class="{red: $root.navTab===0}" ui-sref="first">first</a>
    <a ng-class="{red: $root.navTab===1}" ui-sref="second">second</a>
    <div ui-view></div>
</body>

Remember to update $rootScope in your controllers:

.controller('NavCtrl', function($scope, $rootScope) {});

.controller('FirstCtrl', function($scope, $rootScope) {
    $rootScope.navTab = 0;
});

.controller('SecondCtrl', function($scope, $rootScope) {
    $rootScope.navTab = 1;
});

Your state definitions remain straightforward:

.state('first', {
    url: '/first',
    templateUrl:  'first.html',
    controller: 'FirstCtrl'
})
.state('second', {
    url: '/second',
    templateUrl:  'second.html',
    controller: 'SecondCtrl'
})

Check out Plunker for a demo.

In an ideal scenario, create a directive for this task to avoid reliance on $rootScope. One approach is to broadcast a message upon navigating to a new page, then have the tab directive listen for that event and activate the appropriate tab.

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 preventing the buttons from filling the entire space of the parent element in this case?

https://i.stack.imgur.com/kbiWi.png I'm trying to figure out how to make the Repos and Stars buttons fill the entire height of their parent container, similar to the Github icon. Unfortunately, the code below is not achieving this effect. I attempted ...

Exploring the depths of deep populating in Mongo and Node.js

I am currently struggling with a complex data population issue. var commentSchema = mongoose.Schema({ name: String }); var userSchema = mongoose.Schema({ userId: { type: String, default: '' }, comments: [subSchema] }); var soci ...

It seems like the method has already been executed despite encountering an unexpected end of JSON input error

Currently, I am utilizing the etherscan API to retrieve logs for certain events. Although my JSON parsing method seems quite traditional, an error is being thrown stating "unexpected end of JSON". function getEventHistory() { const topic0 = web3.util ...

I encountered an issue with route handlers in Next.js version 13.2. Sadly, they are not

I am trying to implement an API on my website with the endpoint /api/popular-movie. Here is an overview of my file structure: https://i.stack.imgur.com/e8Pf8.png Additionally, this is my route.ts code: import { NextResponse } from "next/server"; ...

Tips for keeping a reading item in place while scrolling

To enhance the user experience, I would like to improve readability without affecting the scroll position. Question: Is there a way to fix the scrolling item at a specific position (item with the .active class)? I am looking to maintain a consistent read ...

What is the best approach to restructuring this code with an excessive number of $routeProvider routes in a single file?

After researching how to effectively wire up Angular with Express + Node, I stumbled upon a helpful article. One key takeaway was the ability to serve Angular templates from the same directory as views using the line of code: app.set('views', _ ...

Tips for automatically filling in user-entered form values in AngularJS in the event of a failed REST API call

I have created an AngularJS form that includes dropdowns and text boxes. Once the user submits the form, I intend to call a REST API to save the entered values. However, I am unsure how to handle the scenario where the insertion fails. How can I repopula ...

Utilizing Ajax technology to load script in Tapestry 5

I have two components, a "DirectoryViewer" and a "MediaViewer", that I created. The Directory Viewer displays a list of file names and contains a MediaViewer component to show the selected file. This setup is functioning properly. Within the DirectoryView ...

How can I properly reset a timeout duration?

I'm currently working with a function that looks like this: function blabla(){ ... setTimeout(() => { //do some stuff }, 10000) } My question is, how can I reset the time of the timeout (10000) if the function was called and ...

How can we implement :focus-within styling on Material-UI Select when the input is clicked?

I am currently implementing a Select component inside a div element: <div className="custom-filter custom-filter-data"> <DateRangeIcon className="search-icon"/> <FormControl variant='standard& ...

Ensure that each item rendered in a VUE.js v-for loop is distinct and not repetitive

I have obtained a JSON formatted object from a Web API that contains information about NIH funding grants. Each grant provides a history of awards for a specific researcher. My goal is to display only the latest award_notice_date for each unique project ...

Utilize the same controller and view for both searching and non-searching functionality within Angular

Currently, I am developing an Angular application that consists of a single controller and view. I am facing the challenge of wanting to display the same view with or without a search field, based on user preference. My idea is to pass an extra parameter ...

Make the mp3 file automatically download/save as by forcing the link

My website has links to mp3 files using normal <a href="file.mp3"> tags. However, many users with Apple Quicktime installed experience the mp3 files opening instead of saving when clicking on the links. Is there a way to force the browser to save t ...

AngularJS: dual occurrence of stateChangeStart without stateChangeSuccess

I encountered a challenge while developing a simple code for managing user roles. There are certain parts of my back-office that are restricted for guests but accessible to admins. The issue arises with the "stateChangeStart" function in the run code. Lo ...

"Autocomplete disable" feature malfunctioning on the final input field of all web pages

I'm dealing with a web application that has a login page. The username and password fields have the autocomplete attribute set to "off," as well as other variations like nope, new-password etc. However, it's still not working in Chrome version 62 ...

The MTM test runner is failing to identify AJAX callbacks

During my manual testing, I encountered an issue where the recorded test would get stuck after a button click and not proceed to the next page, causing the test to fail. This problem also occurred in CUIT, but I was able to resolve it using Ross McNab&apos ...

Hiding divs toggle off when either all or only one is selected

In a certain page, there is a script that displays a div when a user selects an option. The script functions correctly, except for a scenario where if the user selects 'd' (which shows 'a', 'b', and 'c'), and then se ...

Create a selection menu in an HTML dropdown list using unique values from a JSON object that is separated by commas

I'm working with a JSON object that contains multiple key value pairs, one of which is the Languages key. This Languages key holds comma-separated values such as "English, Hindi, French," and so on. My goal is to extract distinct values from the Lang ...

Deactivate a chosen anchor button when clicked within a loop of elements

In my laravel project, I have a foreachloop that is rendering multiple buttons. I want to disable or remove only the button that is clicked, so I tried the following code: @foreach() <a onclick="remvebtn()" class="btn">My ...

WebSocket functionality in Node.js utilizing the ws module from npm

I am currently working on developing a chat application. The first step involves the user sending their username, and if the name does not already exist, they are logged in. The user can then send a message to another user. However, an issue arises where a ...