Adding default parameters in AngularJS Route-UI is a useful feature for setting up

Using angular UI-Router in my app, I've set up my base language as English.

I have both English and Hebrew locals, and I want to avoid adding parameters to the URL if the language is English.

For instance:

  • Home English --> http://example.com/
  • Home Hebrew --> http://example.com/he/

  • About us English --> http://example.com/about

  • About us Hebrew --> http://example.com/he/about

Is there a way to achieve this?

This is how my current code looks like:

$stateProvider
        .state('/', {
            url: "/",
            templateUrl: "Assets/app/templates/home.html",
            controller: 'homeController'
        })
        .state('activity', {
            url: "/activity",
            templateUrl: "Assets/app/templates/gallery.html",
            controller: 'galleryController'
        })
        .state('page', {
            url: '/:pagename',
            templateUrl: "Assets/app/templates/page.html",
            controller: 'pageController'
        });

Answer №1

Discover a fully functional plunker here

You can achieve this with the help of UI-Router. Start by creating a super parent state named 'root', with a parameter called lang

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

One key feature is using regular expressions in the url to limit matching lang options (such as English, Hebrew, and Czech):

url: '/{lang:(?:en|he|cs)}',

Learn more about it here.

Utilize params : {} setting to specify default value as 'en', with option to be squashed if there's a match with 'en' param value:

params: {lang : { squash : true, value: 'en' }}

Read more at this link or here

The root state serves as the parent to all other states, simply defined by adding parent : 'root':

.state('home', {
    parent: 'root', 
    url: "/",
    templateUrl: "Assets/app/templates/home.html",
    controller: 'homeController'
})
.state('activity', {
    parent: 'root', 
    url: "/activity",
    templateUrl: "Assets/app/templates/gallery.html",
    controller: 'galleryController'
})
.state('page', {
    parent: 'root', 
    url: '/page/:pagename',
    templateUrl: "Assets/app/templates/page.html",
    controller: 'pageController'
});

These navigation links will now function properly:

ui-sref for English:

<a ui-sref="home({lang: 'en'})">home({lang: 'en'})</a>
<a ui-sref="activity({lang: 'en'})">activity({lang: 'en'})</a>
<a ui-sref="page({pagename:'one', lang: 'en'})">page({pagename:'one', lang: 'en'})</a> 

ui-sref for Hebrew:

<a ui-sref="home({lang: 'he'})">home({lang: 'he'})</a>
<a ui-sref="activity({lang: 'he'})">activity({lang: 'he'})</a>
<a ui-sref="page({pagename:'two', lang: 'he'})">page({pagename:'two'})</a>

href for English:

<a href="#/">#/</a>
<a href="#/activity">#/activity</a>
<a href="#/page/three">#/page/three</a>

href for Hebrew:

<a href="#/he/">#/he/</a>
<a href="#/he/activity">#/he/activity</a>
<a href="#/he/page/three">#/he/page/three</a>

See it live in action here

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 the best way to assign an index to each ng-repeated item in order to use it for a ng

Is there a way to implement ng-click in order to retrieve the current index of a thumbnail image in a gallery? I have a gallery with thumbnails, and when a thumbnail is clicked, I want the main image to display the full version corresponding to that thum ...

Anticipating the execution of pool.query within a callback function in the Express framework

Within an Express post endpoint, I am utilizing crypto.generateKeyPair. After generating the key pair, I wish to store it in my database and then return the ID of the inserted row within the same endpoint. Here is the code snippet for the endpoint: app.p ...

Tips for controlling the embla carousel based on breakpoints in a React application

Trying to toggle the Embla Carousel on and off based on different breakpoints using the React version. I have attempted to initialize it for mobile and destroy it for tablet upwards, but it seems like the reinitialization is not working as expected. I su ...

Maximizing the potential of NPM modules by harnessing the power of the package.json file

Currently, I am working on developing an NPM module for a command-line tool. Upon installation of the package, it is essential to access and read the user's package.json file. While I understand how to read the file syntactically, my main concern lies ...

Having trouble with moving the svg:svg element?

I'm struggling to move an svg element that is nested within another svg. I am trying to directly manipulate the x and y values, but I keep encountering a "read-only" error. I attempted to use transform instead, but it doesn't seem to have any eff ...

Display the accurate duration based on the dates selected in an HTML form automatically

If someone has office hours on Monday, Wednesday, and Friday from 7:00 am to 7:00 pm, and on Tuesday and Thursday from 10:00 am to 9:00 pm, the dropdown menu should display only the timings of 7:00 AM to 7:00 PM if the selected date is a Monday, Wednesda ...

How to implement div scrolling on button click using Angular 4

Is there a way to make the contents of a div scroll to the left when one button is clicked and to the right when another button is clicked? I've tried using ScrollLeft, but it doesn't seem to be working... Here's the HTML code: <button ...

What is the best way to locate an element with the class name being an email address using jQuery?

Is it possible to locate an element with an email address as the class name, considering that the email address varies? $(document).ready(function(){ //not working getting error var email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Troubleshooting: Else block not functioning as expected within a React JS map function

I have a notification feature that makes an API call every 10 seconds to display an alert based on the response. However, I'm encountering an issue where the div is not being rendered properly. The div should be displayed based on certain conditions w ...

Limit the Datepicker in MUI (v5) to only accept two-digit years

I am currently using the MUI (v5) Datepicker for capturing user birthday information. The Datepicker has been localized to German language, resulting in the input format DD.MM.YYYY. However, many German users prefer using a shorter year format like DD.MM. ...

Differences between applying addClass(undefined) and addClass(null)

At times, it crosses my mind to include a class in a chain, depending on certain conditions. What would be the most fitting semantic value to add no class? For instance: $(".element").performAction().addClass(condition ? "special-class" : undefined).perf ...

Switch app engines in real-time based on the URL path with express framework

How can I dynamically set App Engine based on the URL? In my application, I have two render engines available: serverSideRenderEngine & browserRenderEngine If the URL is /home, the app.engine should be set as serverSideRenderEngine If the URL is /l ...

Include the aria-labelledby attribute in the jQuery Datatable Pagination

Check out the HTML output created by the Jquery Datatable plug-in for pagination(https://datatables.net/plug-ins/pagination/full_numbers_no_ellipses): <div class="dataTables_paginate paging_full_numbers" id="my-table_paginate" aria-l ...

Tips for enabling mouse wheel zoom on a three.js scene

I have a straightforward three.js graphic that I wanted to make zoomable by using the mouse wheel. I attempted to implement solutions from this and this question in order to achieve this feature. Ideally, I want users to be able to zoom in or out of the gr ...

An array of objects in JavaScript is populated with identical data as the original array

I am attempting to gather all similar data values into an array of objects. Here is my initial input: var a = [{ name: "Foo", id: "123", data: ["65d4ze", "65h8914d"] }, { name: "Bar", id: "321", data: ["65d4ze", "894ver81"] } ...

Retrieving a collection of data from MongoDB featuring today's date

How can I retrieve a list of items from MongoDB with today's date dynamically instead of hardcoding the date in my pushups.js file like "date":"2017-10-26T07:09:36.417Z? Take a look at the code snippet below: Here are the documents in my MongoDB: { ...

Ensuring Input Integrity: Utilizing HTML and Javascript to Block Unfilled Form Submissions

Currently, I am working on developing a registration page using HTML and JavaScript. Although I have added the 'required' tag in HTML to prevent users from submitting empty input fields, I noticed that users can bypass this restriction by simply ...

How can I determine in JavaScript if the Backspace key is being long pressed on iOS or Android devices?

In the process of developing a web application using Vue.js, I encountered an issue with detecting long presses of the Backspace key on desktop keyboards (Windows PCs specifically). On desktop, the event triggers multiple times as long as the Backspace key ...

Adjusting the maxContentLength and maxBodyLength values in Axios

While utilizing the "Axios" library to invoke a WCF method with file information and content as parameters, I encountered an issue. The file is read and transmitted as a base64 encoded string. However, when the file size surpasses a specific limit, Axios t ...

Vue.js: Issue with updating list in parent component when using child component

I'm encountering an issue when utilizing a child component, the list fails to update based on a prop that is passed into it. When there are changes in the comments array data, the list does not reflect those updates if it uses the child component < ...