Ways to determine the current page I am viewing

I am working with a list of tabs and I need to track my current location every time I click on a specific tab. My MainCTRL controller, which is the parent of all tab controllers, needs to be aware of the active tab at any given moment. I attempted to use ng-click event along with $location.path() service to retrieve the current path. However, the issue I encountered was that it initially displayed the previous path instead of the current one. For demonstration purposes, I have included the code snippet below along with a corresponding codepen: http://codepen.io/Barak/pen/wGPpoZ

The reason for this requirement is that I want certain common buttons in the header to be disabled for a specific set of tabs while active for another group of tabs.

var app = angular.module('app',[]);

app.controller("MainCTRL",["$scope","$location", function($scope,$location){
    $scope.title = "Hello World";
    $scope.onWhichPageIAM = function(){
      console.log("He clicked me");
      console.log("location:",$location.path());
      
      }
  
  }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<nav id="tabs_navbar" class="navbar-collapse collapse" ng-app="app" ng-controller="MainCTRL">
    <ul class="tabs">
        <li class="tabs-item">
            <a href="#/AnalyticsSummary" class="tabs-link">Analytics Summary</a>
        </li>
        <li class="tabs-item">
            <a href="#/TDCG" class="tabs-link" ng-click="onWhichPageIAM();">TDCG</a>
        </li>
        <li class="tabs-item">
            <a href="#/keygas" class="tabs-link" ng-click="onWhichPageIAM();">Key Gas</a>
        </li>
        <li class="tabs-item">
            <a href="#/DuvalTriangle" class="tabs-link" ng-click="onWhichPageIAM();">Duval Triangle</a>
        </li>
        <li class="tabs-item">
            <a href="#/DuvalPentagon" class="tabs-link" ng-click="onWhichPageIAM();">Duval Pentagon</a>
        </li>
        <li class="tabs-item">
            <a href="#/NEI" class="tabs-link" ng-click="onWhichPageIAM();">NEI</a>
        </li>
        <li class="tabs-item">
            <a href="#/PTX" class="tabs-link" ng-click="onWhichPageIAM();">PTX</a>
        </li>
        <li class="tabs-item">
            <a href="#/GasTrends" class="tabs-link" ng-click="onWhichPageIAM();">Gas Trends</a>
        </li>
        <li class="tabs-item">
            <a href="#/DataTable" class="tabs-link" ng-click="onWhichPageIAM();">Data Table</a>
        </li>
        <li class="tabs-item">
            <a href="#/Playground" class="tabs-link" ng-click="onWhichPageIAM();">Playground</a>
        </li>
        <li class="tabs-item">
            <a href="#/AnalyticsSettings" class="tabs-link" ng-click="onWhichPageIAM();">Analytics Settings</a>
        </li>
    </ul>
</nav>

Answer №1

If you want to avoid using ng-click, consider utilizing the $routeChangeSuccess event suggested by @Daniel Beck. This event is broadcasted on the $rootScope and can be implemented like so:

app.controller("MainCTRL",['$rootScope', "$scope","$location", function($rootScope, $scope,$location){
  $rootScope.$on('$routeChangeSuccess', function(ev, current, previous) {
    console.log("State change success");
    console.log("location:", current); // information related to the current state.
  });
}]);

Answer №2

To retrieve the current tab, you can utilize the $state variable within your AngularJS application.

<div class="btn-group">
        <button class="btn btn-primary btn-sm" uib-btn-radio="'mytabs'" ui-sref-active="active" ng-model="ActiveChild" ui-sref="tab1">FirstTab</button>
        <button class="btn btn-primary btn-sm" uib-btn-radio="'mytabs'" ui-sref-active="active" ng-model="ActiveChild" ui-sref="tab2">SecondTab</button>

</div>

In your controller, assign the active tab name to $scope.ActiveChild with

$scope.ActiveChild = $state.current.name;
.

The active tab's name can then be accessed using $state.current.name;.

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

Adjust the header's alignment to seamlessly coincide with the uppermost part of the

I'm encountering this peculiar issue with a website I recently started designing. My aim is to make the header perfectly aligned with the top of the page. However, despite my attempts, there persists a stubborn gap that measures around 20px, defying a ...

Tips on adjusting the hover color in the data grid

I want to adjust the color of the Datagrid when hovering over it, does anyone know how to do this? The default color displayed is light blue, but I would like to change it to a different color. Can someone please assist me with this? Looking for document ...

Creating a Custom Error Object in Feathersjs: A Step-by-Step Guide

If I were to throw a GeneralError when calling a service, how can I create an error object with the following structure: { "status": "Failed", "code": "500_1", "detail": "Something is wrong with your API" } I have attempted to add this in the error hook: ...

Ensuring draggable div remains fixed while scrolling through the page

I am currently working on creating a draggable menu for my website. The menu is functional and can be moved around the page as intended. However, I have encountered an issue where the menu disappears when scrolling down the page due to its position attrib ...

Error in Javascript: Null Object

I have created an upload page with a PHP script for AJAX, but I'm encountering errors in Firebug. Also, the upload percentage is not being returned properly. Currently, I can only do one upload in Firefox and the script doesn't work in Chrome. H ...

What is the best way to wait for the state to be set before mapping the array

I have some data stored in an array (shown in the screenshot below) that I am trying to map, but I am facing issues accessing it as it is loaded asynchronously. How can I await the data? Is there a way to achieve this within the render function? render() ...

The navbar toggler icon is not displaying

<header class="container"> <div class="container pt-3 col-md-5 col-sm-5 col-xs-6 text-center"> <a href="#" class="site-logo"><img src="#"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" ...

What is the best way to set a default selected value in an input text box?

Incorporating the typeahead feature into my project has been incredibly useful: <input type="text" ng-model="customPopupSelected" placeholder="Custom popup template" uib-typeahead="state.id as state.desc for state in states | filter:{name:$viewValue ...

Python is the way to go for clicking on a link

I have a piece of HTML and I am in need of a Python script using selenium to click on the element "Odhlásit se". <div class="no-top-bar-right"> <ul class="vertical medium-horizontal menu" dat ...

Skipping the validation of a variable in a return statement with Angular and Javascript

Is there a way to exclude level a.3 from the return in the completion form if a.3 is undefined? scope.isValid = function() { return a.1 && a.2 && a.3; }; ng-disabled="!isValid()" ...

ClassSerializerInterceptor in NestJS does not show the _id field

I am encountering an issue with properly exposing the _id when using the Serializer. Here is my current setup: @UseInterceptors(ClassSerializerInterceptor) @SerializeOptions({ strategy: 'excludeAll' }) This is how I defined the Class: export cl ...

Refreshing Django HTML table dynamically upon database updates

Currently, I have an HTML table set up using a Django template to showcase data from my database. I am looking to ensure that this table remains updated in real-time whenever the database undergoes changes. Despite my research efforts, there is limited inf ...

Can someone provide a method to access the namespace of an Angular controller when utilizing the "Controller As" format?

Imagine you have an AngularJS ngController directive set up like this: <div ng-controller="SomeCtrl as herpderp">…</div> Is there a way to extract the namespace ("herpderp") from within the SomeCtrl controller itself? This could be useful f ...

Is it possible to use next.js to statically render dynamic pages without the data being available during the build process?

In the latest documentation for next.js, it states that dynamic routes can be managed by offering the route data to getStaticProps and getStaticPaths. Is there a way I can create dynamic routes without having to use getStaticProps() and getStaticPaths(), ...

Loop stops after completing one iteration

I am currently working on a program that automatically generates ASCII text based on input numbers. Essentially, when a number is provided as input to the function, it will be displayed as magnified ASCII text. For example, an input of 0123456789 would gen ...

Tips for effectively utilizing JavaScript regex to precisely match a string before triggering the submit button

I have a form in Angular with a text input field that requires the entry of lowercase letters separated by commas, like this: c, d, e, g, a, f etc... Currently, the submit button activates as soon as any part of the input matches the required format, allo ...

The display and concealment of a div will shift positions based on the sequence in which its associated buttons are clicked

I am in need of assistance with coding (I am still learning, so please excuse any syntax errors). What I am trying to achieve is having two buttons (button A and button B) that can toggle the visibility of their respective divs (div A and div B), which sh ...

Tips for inserting a PHP variable into an SQL query

Here is the code I'm currently working on: <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">WebSiteName</a> < ...

Arranging several lists in a row without any specific order

I am trying to arrange multiple <ul> elements on the same line to create a shop-like display for products. Currently, I have set up several unordered list tags: ul { display: inline; } li { list-style: none; } <ul> <li>& ...

When I hover over my divs, my span is positioned behind them

Greetings, I apologize for any language barriers. I will do my best to articulate my issue clearly. I have experimented with various approaches and reviewed similar questions, but unfortunately, I am unable to resolve the problem... I have created a title ...