Update the controller to modify the route parameter

I've defined my state like this:

stateProvider
        .state('app', {
            templateUrl: 'views/layout.html',
            url: '/:lang/app',
            resolve: {
                lang: ['$rootScope', '$stateParams', function(rootScope, stateParams){
                    return stateParams.lang;
                }]
            }
        });

In my UI, I have language buttons that need to navigate to the same URL but with a different language parameter:

<a ui-sref="???({ lang: 'en' })"> English </a>

Is there a way to achieve this?

Answer №1

Creating a custom directive for handling state parameters:

angular.module('app').directive('uiSrefParams', ['$state', function(state){
    return {
        restrict: 'A',
        link: function(scope, element, attrs){
            element.click(function(){
                var params = scope.$eval(attrs['uiSrefParams']);
                state.go(state.$current, params);
            });
        }
    };
}]);

Example of usage:

<a ui-sref-params="{ lang: 'en' }"> English </a>

Answer №2

This particular functionality is actually already integrated within the ui-router.

1) You can find detailed documentation on this feature here:

ui-sref='stateName' - Allows navigation to a state without any parameters. The 'stateName' parameter can refer to any valid absolute or relative state, following the syntax rules of $state.go()

2) Further information can be accessed from this document as well:

The destination state for transition or a relative path of the state. If the path begins with ^ or ., then it is relative; otherwise, it is considered absolute.

Here are some examples:

$state.go('contact.detail') will navigate to the 'contact.detail' state
$state.go('^') will take you to a parent state.
$state.go('^.sibling') will move to a sibling state.
$state.go('.child.grandchild') will lead to a grandchild state.

3) Also, there is a demonstration available through a plunker, showcasing how this feature can be easily utilized:

By having 2 states (the aforementioned one plus its 'app.child'), you can apply this syntax within the 'app' state

<a ui-sref=".({ lang: 'en' })"> English </a> 
<a ui-sref=".({ lang: 'cz' })"> Czech </a>
<a ui-sref=".child({ lang: 'en' })"> Child English </a> 
<a ui-sref=".child({ lang: 'cz' })"> Child Czech </a>

This same approach could be implemented in the child state as well:

<a ui-sref=".({ lang: 'en' })"> Sibling English </a> 
<a ui-sref=".({ lang: 'cz' })"> Sibling Czech </a>

Feel free to explore the example link to see it all in action...

EXTEND: Additional insights can be found in the note shared within the ui-sref documentation

A point to consider regarding relative ui-sref targets:

You have the option to use relative state paths within ui-sref, similar to the way relative paths are used in state.go(). It's important to remember that the path is relative to the state where the link is located, meaning the state that loaded the template containing the link.

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

Error encountered during the building of a Java project using Gradle

I ran into an issue with Git Bash error output (build failed). Despite attempting to resolve it by installing Python as suggested, setting the Python environment variable in IntelliJ, and following other recommendations, I still encounter the same build ...

AngularJS employs the identical service as the model but with distinct data

As I develop a factory service that offers several functions, here's an example of how it could be structured: var myApp = angular.module('panelServices', ['ngResource']); myApp.factory('myService', [...]{ function m ...

A pattern matching formula to eliminate specific characters from the beginning to the end of a string

I am facing an issue with extracting content from a given string: var string = "From: Sarah<br /> Sent: 10 May 2021 09:45:20</br /> To: Alice<br /> Subject: Meeting Reminder<br /><br /> Hi Alice, <br /> Here is a ...

Incapable of inputting text to communicate with chatbot users

Description Incorporating a chatbot into the Flask-based backtesting platform involves utilizing a sidebar toggle button on the right side. By clicking this button, users can reveal the sidebar containing the chatbot. Expected Behavior Users should ...

Tips for aligning a dropdown button with the other elements in your navbar

I followed the code outline from a tutorial on We3schools, but I'm having an issue with the button not aligning correctly with the navbar. https://i.sstatic.net/fSRIT.png I attempted to adjust the code for proper alignment before publishing, but was ...

What is required to run npm rebuild node-sass --force following each instance of a `yarn add` command?

As I attempt to set up the isemail npm library, everything appears to be going smoothly. However, when I execute yarn start:dev, which essentially runs "npm run build:dev && ./scripts/gendevconfig.sh && cross-env BABEL_DISABLE_CACHE=1 NODE_ ...

What could be causing my jQuery event handler to not work properly when connected to numerous elements?

I have implemented jquery to dynamically add multiple "addTask" form elements to a "ul" on the webpage every time a link is clicked. $('span a').click(function(e){ e.preventDefault(); $('<li>\ <ul>\ ...

Prevent the bootstrap dropdown menu from closing when encountering a login error during form validation using ajax and codeigniter

I encountered an issue with my dropdown menu login that utilizes bootstrap ajax and codeigniter. When I attempt to submit the form and there is an error, I have to click multiple times before the error message appears because the dropdown menu keeps closin ...

The completion event for Ajax and Json does not activate Google Maps

I'm currently facing an issue with my Google Maps functionality. Despite trying various solutions that involve hidden tabs, the problem persists. The trouble lies in the fact that my ajax function successfully posts and retrieves data, but fails to tr ...

What is the best way to turn off ajax functionality when detecting IE8?

Encountering a significant problem where every time the save/cancel button is clicked, IE8 freezes (while Firefox and Chrome work without issue). When JavaScript is disabled in the browser, it works correctly. There is a suspicion that an ajax call linke ...

Struggling to run this unit test (for a helper) smoothly - AngularJS, Karma, Jasmine - Any tips?

As a newcomer to Angular and Karma, the abundance of conflicting advice on how to write unit tests is making things incredibly confusing for me. Any help you can offer would be greatly appreciated! I am currently working on a helper class that relies on a ...

Using JQuery to automatically scroll and anchor to the bottom of a dynamically populated div, but only if the user doesn't

I am attempting to achieve the functionality of automatically scrolling to the bottom of a div with the ID #chat-feed. The overflow for this div is set to auto, and I want it to remain at the bottom unless a user manually scrolls up. If they do scroll up, ...

One way to enhance user experience is by passing parameters dynamically from the database when an element is clicked. This allows for the retrieval of

Earlier, I tried to post a question but couldn't get it working due to incorrect code. As the title suggests, my objective is to retrieve data from a database and display it in a div. The idea is that when this data is clicked, it should be passed to ...

Unable to load CSS styles from SCSS when rendering the view

I am having trouble loading styles on my webpage from SCSS. Below is the code from my Gulp.js file: // Compile and Automatically Prefix Stylesheets gulp.task('styles', function () { return gulp.src([ 'Content/styles/**/*.scss&apo ...

The ng-switch function is not generating the desired code output

In my Ionic app, I have the following code snippet that I am currently viewing with ionic serve. However, when the initial ng-switch statement triggers... <span ng-switch="post.enclosure"> <span ng-switch-when="[]"> <p>def&l ...

AngularJS and JQuery: smoothly navigate from current position to specified element

This particular directive I am currently implementing was discovered as the second solution to the inquiry found here - ScrollTo function in AngularJS: .directive('scrollToItem', function($timeout) { ...

Triggering an error message when a user attempts to submit an incomplete angular form

Working on an Angular form where users advance to the next step by clicking a button, but it remains disabled until all fields are valid. I'm wondering how I can implement a custom class to highlight incomplete fields when the user tries to move to t ...

Combining numerical values within an array using JavaScript

Below are different buttons ranging from 1 to 9 that I have: <button type="button" onclick="calculatorNumber(1)"> When clicked, the following function is triggered: function calculatorNumber(i) { myNumbers.push(i); var x = document.getElem ...

Trouble accessing Facebook Messenger through the integrated browser on Facebook network

My goal is to promote a webpage by sharing it on Facebook Messenger. While everything works smoothly on desktop and mobile browsers, the issue arises when using Facebook's built-in browser - the Facebook Messenger app fails to open and the page just r ...

Using Angular and Laravel to display JSON data extracted from a MySQL database

I am currently retrieving data from MySQL using Laravel query builder, converting it to JSON format as per the suggestion of W3schools. However, when trying to display the fetched data using AngularJS, I end up with a blank page. Laravel route Route::ge ...