Choose the url path using UI-Router option

In my Angular project, I am implementing a complex structure of nested states using UI-Router.

I am working on setting up a parent state that will determine the language of the application based on an optional locale path in the URL.

  • For Spanish www.website.com/es/search
  • For English www.website.com/search

The '/es' is required for Spanish, while English is assumed when the parameter is missing and I would like to avoid having the '/en'.

I want all child states of this parent state to inherit the selected locale value.

$stateProvider
    .state('localization', {
        abstract: true,
        url: '/:locale?',
        params: {
            locale: { value: 'en' }
        }
    })
    .state('search', {
        url: '/search',
        parent: 'localization'
    });

I aim to access the $stateParams.locale in any of the child states seamlessly.

Answer №1

If you're looking for a similar Q & A, you can refer to this post on Stack Overflow about AngularJS routing: Angular js - route-ui add default parmeter or check out another solution here.

To solve the issue, consider creating a root state like the following:

.state('localization', {
    url: '/{locale:(?:en|es|cs)}',
    abstract: true,
    template: '<div ui-view=""></div>',
    params: {locale : { squash : true, value: 'en' }}
})

Subsequent child states can simply use this as their parent:

.state('home', {
    parent: 'localization', // the parent state will handle it
    url: "/",
    ...
})
.state('activity', {
    parent: 'localization',
    ...

You can also check it out here, where there is a fully functional Plunker example.

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

Tips for locating an element beyond the page source with Puppeteer

My goal is to extract specific information from a webpage by utilizing this code snippet to target an element and retrieve certain values within it: const puppeteer = require('puppeteer'); function run (numberOfPages) { return new Promise(a ...

What considerations should be made for localizing JavaScript files in Django?

When translating a Django application, the makemessages command is used to parse TXT, HTML, and PY files and generate PO files. However, when it comes to localizing JS files, the djangojs command must be run separately. I haven't had a chance to explo ...

Restoring the position of the <Rect/> element after dragging in a React + Konva application

In my attempt to make a Rect component snap back to its original position using ReactKonva, I defined a Toolbar class with certain dimensions and initial positions for the rectangle. However, after dragging the rectangle and attempting to reset its positio ...

What methods does MaterialUI utilize to achieve this?

Have you checked out the autocomplete feature in their component? You can find it here: https://mui.com/material-ui/react-autocomplete/ I noticed that after clicking on a suggestion in the dropdown, the input box retains its focus. How do they achieve thi ...

Tips for avoiding multiple function calls in React JS when a value changes

How can I avoid multiple function calls on user actions in my demo application? I have tabs and an input field, and I want a function to be called when the user changes tabs or types something in the input field. Additionally, I need the input field value ...

Discover the sequence that is the smallest in lexicographical order possible

Here is the question at hand Given a sequence of n integers arr, find the smallest possible lexicographic sequence that can be obtained after performing a maximum of k element swaps, where each swap involves two consecutive elements in the sequence. Note: ...

Struggling to create an access token with the Slack API

My goal is to retrieve an access token from the Slack API. When I use the code provided below, it generates an authorization URL containing a temporary code in the query string. Once permissions are granted, the process redirects to /slack/oauthcallback. ...

Having trouble sending specific data using the jQuery Form Plugin ajaxForm feature

Currently, I am utilizing two jQuery plugins: plupload and jQuery Form Plugin ajaxForm. Everything is functioning well except for one issue: I am unable to send the file.name (using ajaxForm) of a previously uploaded file with plupload. To elaborate more ...

Improving Mysql Table Performance for Efficient Filtering and Eliminating Filesort Operations

I am currently developing a quiz application using Angular, with Node.js and MySQL as the backend. Within the Quiz question table, there are fields such as id, title, choice_a, choice_b, choice_c, choice_d, subject_id fk, topic_id fk, rand1, rand2, and ran ...

Unable to save data retrieved using jQuery JSONP

My current project involves fetching photo data from Flickr using a jQuery AJAX call with JSONP. However, instead of immediately using the data, I want to store it for future use. In some cases, users will be able to perform different queries on the pre-fe ...

Unique title: "Implementing Unique Event Handlers with VueJS Components"

My VueJS and Buefy project begins with two distinct click actions: Click on the Cyan area -> redirects to another page (Action 1) Click on the Magenta area -> shows a dropdown menu (Action 2) https://i.stack.imgur.com/AVLOS.png However, when clic ...

Node.js throws an error with the message "Unexpected token *" while utilizing the robe

Currently, I'm working on a Node.js application where I'm attempting to utilize the node module named robe. Unfortunately, I encountered an error message when trying to launch the app: function* promiseToGenerator(promise) { ^ Error l ...

What is the best way to ensure a consistent time interval between invoking two functions in JavaScript?

Is there a way to create a code that will call one function, let's say toStart(), and then immediately call another function, toStop(), exactly two seconds after the first function is initiated? I want this process to continue until a specific button, ...

Sorry, we encountered a snipcart issue: The public API key was not found. To fix this, please ensure that the attribute data-api-key is

I'm experiencing issues with loading Snipcart correctly. It's able to detect the API key on localhost and display the number of items in the cart, but when deployed to Netlify, it briefly shows the item count before displaying the error message: ...

The jQuery UI Sortable functions are being triggered at lightning speed

I am currently working on a project where users can create a seating chart, add rows and tables, and move the tables between different rows. The functionality for adding rows and moving tables already exists in the code. However, I am facing an issue where ...

The process of altering the color of a table row in JavaScript can be done after dismissing a pop-up that was triggered by a button within the same row

I am tasked with changing the color of a specific table row based on user interaction. The table consists of multiple rows, each containing a button or image. When the user clicks on one of these buttons or images, a popup appears. Upon successful data sub ...

Reveal the MongoDB database connection to different sections within a Next.js 6 application

Currently developing an application using Next.js v6, and aiming to populate pages with information from a local mongodb database. My goal is to achieve something similar to the example provided in the tutorial, but with a twist - instead of utilizing an ...

Tips for defining the operational scope of orbit controls in three.js

I've been working on creating an orientation cube in threeJS and have set up 2 scenes with different viewports, cameras, and controls. Check out the fiddle here var controls = new THREE.OrbitControls( view.camera, container.domElement ); In the fid ...

Objects of equal nature combine and sift through

I am looking to categorize objects based on their status ID and also retrieve data and CSR counts for each item. Each StatusName has multiple items: [ { "StatusId": 2, "StatusName": "ordered", " ...

No data received from XMLHttpRequest

Within my Java Web application, I'm making an ajax request using the following code: <script type="text/javascript"> function selectTableHandler() { console.log("inside selectTableHandler"); var xhttp = new XMLHttpRequest(); var se ...