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

SpineJS combined with Express

Are there any recommended tutorials or case studies showcasing the integration of SpineJS and Express in applications? I have experimented with both technologies, but am currently facing some challenges. My backend is set up to run Express by using coffee ...

Filtering in AngularJS can be done by combining two fields at

I attempted to implement similar code for filtering my tasks, but it seems to be malfunctioning. When I use just one filter, everything works fine regardless of which one I choose. However, when I attempt to filter by the second input, it simply does not w ...

Enhancing the 'grunt build' process with partials for an AngularJS app

Is there a way to modify my Grunt file to ensure that it locates the partial views correctly? The grunt.js file I am using is the default one created when initializing an AngularJS application with Yeoman. It does not include any plugins or jQuery, just A ...

Exploring the power of Angular's $observe and enhancing it with

Currently, I am closely monitoring attribute values by using $observe within a directive. The callback function is triggered when the value of the attribute is changed. However, when I try to update a $scope variable, it does not seem to reflect the change ...

PHP, jQuery, and MySQL combine to create a powerful autocomplete feature for your

I've implemented the source code from into my project, but I'm facing an issue where I can't retrieve any results when typing in the autocomplete textbox. Could someone point out where I might be making a mistake? This is the code I am us ...

Tips for showing only the date (excluding time) from a get operation in javascript (specifically using node js and mysql)

I recently built a CRUD application using Node.js and MySQL. However, I am facing an issue where I am unable to display the date without the time and in the correct format. { "id": 1, "name": "Rick Sanchez", "dob": & ...

Dynamic sidebar that adheres to the content and is placed alongside it using JavaScript

I am in need of creating a sticky sidebar that will float beside my content column. The purpose of this sidebar is to contain jump links on the page, similar to what can be seen on this page, but with the navigation buttons positioned directly next to the ...

The issue of `Console.log` displaying as undefined arises after subscribing to a provider in Ionic3

In the process of implementing the Spotify api into my Ionic 3 app, I encountered an issue where the data retrieved appears as undefined when attempting to log it. Let me share some code and delve deeper into the problem. Here is the function getData() tha ...

My React app experienced a severe crash when trying to render an animation in L

Currently, I am working on a React application that was set up using Vite. I recently incorporated an animation using Lottie, and although I was successful in implementing it, I encountered a problem when navigating between different pages of my applicati ...

Configuring Vuex State

Currently, I have a prop that is being bound to a child component. My goal is to eliminate this binding and instead assign the value to a data property in a vuex global state. <VideoPip :asset="asset" v-show="pipEnabled === true" /&g ...

Simulated script in a different component

I am looking to simulate the functionality of Amazon AWS S3 getObject The specific code I aim to test is located in helper.js var AWS = require('aws-sdk'); var s3 = new AWS.S3(); exports.get_data_and_callback = function(callback, extra){ s3. ...

Exporting Axios.create in Typescript can be accomplished by following a few simple

My code was initially working fine: export default axios.create({ baseURL: 'sample', headers: { 'Content-Type': 'application/json', }, transformRequest: [ (data) => { return JSON.stringify(data); } ...

Guide on triggering a modal upon receiving a function response in React

I am looking for a way to trigger a function call within a response so that I can open a modal. Currently, I am utilizing Material UI for the modal functionality. Learn more about Modals here The process involves: Clicking on a button Sending a request ...

The data being sent to the controller by my Service is not accessible in the expected manner

(function () { angular.module("app").controller('DashboardController', ['$q', 'dashboardService', function ($scope, $q,dashboardService) { var DashboardController = this; dashboardService.retrieveData(DashboardControll ...

Acquiring the index of a selector event within a list of dynamic elements

I am seeking guidance on how to go about solving the issue of obtaining an event index. I have a hunch that closures might play a role in the solution and would appreciate some insights. Initially, I dynamically build an HTML5 video container using an aja ...

How to incorporate user-submitted form data into the existing state using React

I am currently working on a React project that involves a form input. The goal is for the user to input a number into the field, and then take that number and add it to another number in the application's state. For example, if this.state.data initia ...

VueJS: What is the easiest way to create a new instance of a div with just a click of a button?

Is there a way to create a function that will generate a new instance of a specific div (.container in the template) when a button (#addDiv) is clicked, with the button being the only visible element on the webpage initially? I have heard about using docum ...

When it comes to using the jQuery get method, it may not always yield the desired results. However, utilizing it within a form context,

Upon loading my website, users are directed to a file named index.jsp. My goal is to send a get request to one of my servlets when this page loads. The initial URL is: localhost:8080/Test/ The servlet should perform an action when the URL changes to: loc ...

The PHP blocking code in Zend Server not only blocks the response of the current ajax call but also impacts the handling

I encountered a peculiar problem. Suppose I have an ajax call like this; $.ajax({ url:"url1.php", }) Following this ajax call, I have another ajax call as follows; $.ajax({ url:"url2.php", success:function(data){console.log(data);} }) ...

It's possible for anyone to enhance the appearance of the Download button by adding styles without compromising its functionality

Looking to enhance the style of the Download button as it appears too formal. Seeking assistance in adding some button styles to make it more stylish. The code is correct, just aiming to give the Download button a trendy look with specified styles. ...