Revealing the name of the current state using UI router

Seeking a solution to implement a language switcher that seamlessly navigates users from the "en" side to the corresponding "de" page when they click on the language toggle. Currently, I am exploring the $state parameter and noticing that accessing the values I need through the "current" property is viable. However, I encounter some limitations when trying to pinpoint specific values within nested views.

I am considering an approach where, while on a URL like url/en/content, the language navigation dynamically loads destination points into a data attribute. With a custom directive, I aim to trigger a "go to" function and set the preferredLanguage value using angular-translate.

The main challenge lies in extracting the precise $state name; browsing $state reveals the desired values in the current object, but directly accessing $state.current only returns the parent state.

If anyone can suggest a more elegant Angular method (without resorting to custom cookies), I'm open to any recommendations.

Thank you!

Update! CODE SAMPLES:

Object reference of my states:

var urlStates = {
        en: {
            home: {
                name: 'home',
                url: '/en',
                templateUrl: 'templates/'+lang+'/home.html',
                abstract: 'true'
            },
            home_highlights: {
                name:'home.highlights',
                url: '',
                templateUrl: 'templates/'+lang+'/home.highlights.html'
            },
            home_social:
            {
                name: 'home.social',
                url: '/social',
                templateUrl: 'templates/'+lang+'/home.social.html'
            },
            home_map:
            {
                name: 'home.map',
                url: '/map',
                templateUrl: 'templates/'+lang+'/home.map.html'
            }

        };

My States:

$stateProvider
        .state(urlStates.en.home)
        .state(urlStates.en.home_highlights)
        .state(urlStates.en.home_social)
        .state(urlStates.en.home_map);

        $locationProvider.html5Mode(true);

})

Controller:

.controller('LandingPage', function($translate, $state){
    this.state = $state;
    this.greeting = "Hello";
});

And Lastly, the output I see in the dom:

With this.state = $state;

{
    "params": {},
    "current": {
        "name": "home.highlights",
        "url": "",
        "templateUrl": "templates/en/home.highlights.html" },
        "transition": null
}

With this.state = $state.current

{
    "name": "",
    "url": "^",
    "views": null,
    "abstract": true
}

Answer №1

this is my method

JAVASCRIPT:

let app = angular.module('app', ['ui.router']);

app.run( ['$rootScope', '$state', '$stateParams',
                      function ($rootScope,   $state,   $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams; 
}
]);

HTML:

<pre id="uiRouterDetails">
      $state name = {{$state.current.name}}
      $stateParams details = {{$stateParams}}
      $state full URL = {{ $state.$current.url.source }}    
</pre>

DEMONSTRATION

http://example.com/edit/ABC123?p=preview

Answer №2

Responding to your inquiry in this specific manner presents a significant challenge.

However, you inquire about navigation and express concerns regarding the current $state appearing to behave strangely.

In response to the first query, I would consider it being too broad, while for the second concern, it could likely signify an error on your part or overlooking something obvious :)

 

Consider the following controller:

app.controller('MainCtrl', function($scope, $state) {
  $scope.state = $state;
});

Where app is configured as:

app.config(function($stateProvider) {
  $stateProvider
    .state('main', {
        url: '/main',
        templateUrl: 'main.html',
        controller: 'MainCtrl'
    })
    .state('main.thiscontent', {
        url: '/thiscontent',
        templateUrl: 'this.html',
        controller: 'ThisCtrl'
    })
    .state('main.thatcontent', {
        url: '/thatcontent',
        templateUrl: 'that.html'
    });
});

A simple HTML template with

<div>
  {{ state | json }}
</div>

Would display something like the example below

{ 
  "params": {}, 
  "current": { 
    "url": "/thatcontent", 
    "templateUrl": "that.html", 
    "name": "main.thatcontent" 
  }, 
  "transition": null
}

I have provided a brief demonstration illustrating this scenario using ui.router and pascalprecht.translate for the menus. Hopefully, you can derive value from it and identify the issue at hand.

Check out the Plunker here http://plnkr.co/edit/XIW4ZE

 

Screenshot


Answer №3

In the current project I'm working on, the solution is structured like this:

I designed an abstract Language State

$stateProvider.state('language', {
    abstract: true,
    url: '/:language',
    template: '<div ui-view class="lang-{{language}}"></div>'
});

Every state within the project needs to rely on this state

$stateProvider.state('language.dashboard', {
    url: '/dashboard'
    //....
});

The language switch buttons trigger a custom function:

<a ng-click="footer.setLanguage('de')">de</a>

Within the corresponding function (located in a controller), it looks like this:

this.setLanguage = function(lang) {
    FooterLog.log('switch to language', lang);
    $state.go($state.current, { language: lang }, {
        location: true,
        reload: true,
        inherit: true
    }).then(function() {
        FooterLog.log('transition successfull');
    });
};

This method works, but there could be a cleaner solution by simply changing a value in the state params from HTML:

<a ui-sref="{ language: 'de' }">de</a>

Unfortunately, this approach does not function as expected, as mentioned in https://github.com/angular-ui/ui-router/issues/1031

Answer №4

Implementing Timeout Function

$timeout(function () { console.log($state.current, 'Everything is working perfectly'); }, 100);

Check out the discussion on this GitHub thread

Answer №5

I successfully implemented $state with $timeout.

To demonstrate,

(function() {
  'use strict';

  angular
    .module('app')
    .controller('BodyController', BodyController);

  BodyController.$inject = ['$state', '$timeout'];

  /* @ngInject */
  function BodyController($state, $timeout) {
    $timeout(function(){
      console.log($state.current);
    });

  }
})();

Answer №6

The delay in receiving the current state from Angular is simply due to the time it takes to load.

One way to ensure you get the accurate current state is by utilizing the $timeout function, which will provide the correct result in the $state.current.name property.

$timeout(function(){
    $rootScope.currentState = $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

Does the content within {{ }} get monitored for updates on my webpage?

Is there a way to display content on the page without AngularJS constantly checking for changes? Could someone explain how to achieve this? Do I just need to use a label like the following: {{ abc }} ...

Click event doesn't trigger the 'else if' statement in jQuery

Having trouble with a button click issue. In the following code, when the button is clicked, it checks if the text on the button is "day". If so, it changes the background-color of the body to red and updates the button text to "night". I am struggling wit ...

Utilizing nested routes in Node.js with express.js framework!

index.js const AuthRouter = require("./Routes/Auth/signup") app.use("/account", AuthRouter) signup.js router.post("/", async (req, res) => { res.send("Signup") }) It's functioning correctly... H ...

Is it necessary to alter the number of rows or columns in the table?

I'm having an issue with my code where the table is not changing the number of rows based on the selected input option. It seems to only read the first value of the select id and does not update the rows accordingly. Can someone help me identify the m ...

Adjust the DOM based on the output of the function

I'm currently working on creating a list where only one element can be active at a time. The state is updating correctly, but I'm facing an issue with the isActive function. It only activates initially and doesn't trigger when the state chan ...

What are the steps for configuring clusters in an expressjs 4.x application?

I currently have an expressjs generated app that is configured with socket io and I want to incorporate nodejs clusters into it. However, the challenge lies in the fact that in Express 4.x, the server listening configuration now resides in the bin/www file ...

Retrieve the property called "post" using Restangular

With the following code, I am fetching a list of 'postrows': $scope.postrows = {}; Restangular.all('/postrows').getList().then(function(data){ $scope.postrows = data; }); The returned JSON structure is as follows: { id: 1, post ...

Getting the specific key of the selected item from material-ui autocomplete when onSelect is triggered, rather than simply retrieving the value

I am incorporating React with Material-ui and utilizing the Autocomplete component described in detail on this page - https://material-ui.com/components/autocomplete/ using downshift. <Downshift id="downshift-options"> ...

Utilizing the content of an HTML element within Ruby embedded code - a comprehensive guide

Below is the code snippet in question: <% @groups.each do |group| %> <tr> <td id="groupid"><%= group.id %></td> <td><a href="#dialog" name="modal"><%= group.title %></a></td> </tr> &l ...

Sketch a line extending from one element to the next

Is there a way to create a styled line that starts from the center of one <td> element and ends at the center of another? I attempted to use the jQuery Connections plugin but it only connects the edges of the elements, not their centers. The plugin ...

Retrieving the current value of the selected option using JQuery

I am working on a feature where I have different quantities in selects after each button click. <button type="button" class="btn btn-sm btn-primary" id="addtocart2" >Button1</button> <select id="quantity1" class="ml- ...

Next.js deployments on Vercel are encountering issues with resolving local fonts

Currently, I am facing an issue while trying to incorporate next/fonts into my project in next.js 13.3. The setup works perfectly on my local machine, but as soon as I deploy it to Vercel, a build error arises with the message Module not found: Can't ...

The express gateway is unable to transfer multipart/formdata

I've implemented express gateway as my main service gateway. One of the services I have needs to update an image, and when I try to handle files independently using multer it works fine. However, once this service is routed through express gateway, th ...

Utilizing vanilla JavaScript within a React.js component: A step-by-step guide

I have implemented chartist.js in my React component, and I am facing an issue with displaying the chart on the web page. I am following the example provided at Below is the code snippet: var Chartist = { version:'0.9.5' } (function (wind ...

extract the information from a specific div on a different website using JavaScript

My goal is to load a specific div with a class="container" from a website and extract its content into my application. Upon making an ajax call to retrieve the site's data, I encountered a cross-domain origin error since I don't have access to t ...

Guidelines for integrating deep links into a ReactJS Ionic Android application

I have recently converted my ReactJS project into an android project following a tutorial. Now, I have successfully created an APK file and would like to configure the app to open when a specific URL is clicked on a mobile browser. Any guidance on how to a ...

Error: Attempting to access property 'mouseX' of an undefined object was unsuccessful

Currently, I am utilizing AmCharts to generate a graph displaying payments made over time. The configuration setup for AmCharts seems accurate. Just to mention, I do not possess expertise in Javascript. Utilizing AmCharts 3.18.3.free The complete conso ...

`How can I retrieve the previous location path in an AngularJS application?`

Is there a way in AngularJS to check my previous path location from my current one? ...

Increase in textbox size depending on selected dropdown value

Our concept involves offering three choices: Email #1 pulled from the database Email #2 retrieved from the database Input a new email Should the user select option #3, a textbox will expand at the bottom of the dropdown menu for easy entry of a new emai ...

The ng2-dnd library encountered an issue: StaticInjectorError in AppModule with SortableComponent pointing to ElementRef

I have been experimenting with the ng2-dnd sortable container from ng2-dnd. Below is the HTML code for my component: <div class="row"> <div class="col-sm-3"> <div class="panel panel-success"> <div ...