matching equivalent URLs to identical states using an optional parameter in angular-ui-router

I am looking to map the following states to the same routes with a parameter:

/en/live/
/en/


/en/live/football
/en/football

The goal is to store the 'live' part in a variable. I have attempted the following approach:

$stateProvider.state('language.live-lobby', {
    url: "/en/{liveStatus:live|}/football"
}

However, the above method does not allow for specifying an empty parameter. Ideally, /en/live/football would match while /en/football would not. This way, I could access the liveStatus parameter.

Is there a way to achieve this without defining multiple states? I want to avoid creating multiple states as they all require the same information such as views, data, and resolve.

Answer №1

Don't forget to check out this functional plunker

Here are the resources I used:

We can implement this state definition:

.state('language.live-lobby', {
  templateUrl: 'tpl.html',
  //url: "/en/{liveStatus:live|}/football",
  url: "/{lang:(?:en|cz|de)}" +
       "/{liveStatus:(?:live|podcast)}" +
       "/{sport:(?:football|golf)}",
  params: {
    lang:       { squash: true, value: 'en' },
    liveStatus: { squash: true, value: 'live' },
    sport:      { squash: true, value: 'football' },
  }
})

All these links would function as anticipated:

  // these follow defaults
  <a href="#/en/live/">
  <a href="#/en/">
  <a href="#/en/live/football">
  <a href="#/en/football">

  //here we pass some non default
  <a href="#/cz/podcast/">
  <a href="#/cz/">
  <a href="#/cz/podcast/golf">
  <a href="#/cz/golf">

View it 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 embed a variable within a Directive HTML block for seamless access by the Controller?

I am facing a challenge with my custom directive that inserts an HTML block onto the page. The issue is to have a variable within this block that can be manipulated based on an ng-click function in my controller. This is what my directive looks like: .di ...

The characteristics of angular js Service/Factory and how they influence functionality

I'm seeking clarification on the behavior of AngularJS, especially in terms of JavaScript. In my code, I have a controller that has an Angular factory injected into it. Here's a snippet from the controller: $scope.localObjCollection = myObjFac ...

The issue with AngularJS Routing is that it fails to refresh the menu items when the URL and views are being

My current project involves implementing token-based authentication using the MEAN stack. The goal of my application is to display different menu items based on whether a user is logged in or not. When there is no token present, the menu should show option ...

Unable to retrieve data from the JSON file after making a $http.post call

Currently facing an issue with my grocery list item app developed in AngularJS. I have simulated a connection to a server via AJAX requests made to local JSON files. One of the files returns a fake server status like this: [{ "status": 1 }] I am att ...

Error: Google Plus Cross-Origin Resource Sharing Issue

I recently developed an AngularJS application that utilizes Google's server-side flow for authentication. The issue arises when my AngularJS app is hosted on one server and the Rest API is hosted on another. After successfully logging in, I encounter ...

The Angular scope remains stagnant even after applying changes

Having trouble updating a variable in the ng-repeat loop <div ng-controller="MapViewCtrl"> <a class="item item-avatar" ng-href="#/event/tabs/mapView" > <img src="img/location.jpg"/> <span cl ...

Tips for turning on a gaming controller before using it

Current Situation In my ionic side menu app, I have a main controller called 'main view'. Each tab in the app has its own controller, which is a child of the main controller. The issue I'm facing is that when I start the app, the first cont ...

The $q.all() function in angular seems to struggle with resolving properly

Having trouble with 3 $http calls in a factory. Creating 4 promises: var promise = $q.defer(), PBdeferred = $q.defer(), Rdeferred = $q.defer(), Pdeferred = $q.defer(); Making the first call to the API: $http.get('/pendingBills').then(fu ...

The ng-repeat function is iterating through the array multiple times

Using ng-repeat to bind the same array multiple times. JavaScript : $scope.currentitem = item; $scope.currentitemCategory = $scope.currentitem.category.split(','); console.log($scope.currentitemCategory); HTML: <div ng-repea ...

Error: The JavaScript function you are trying to use is not defined

Hi there, I'm new to javascript and angularjs. I've created a function in my controller to open a website when clicking on a button. However, I'm encountering an error message saying ReferenceError: openWebsite is not defined when trying to ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

Top location for Cordova/Phonegap events in AngularJS

Currently, I am working on an AngularJS Cordova app and so far everything is progressing smoothly. My next objective is to integrate Cordova plugins into the application, specifically the Cordova Connect plugin, which will allow me to monitor network conne ...

Navigating Angular's Resolve Scope Challenges

As a junior developer, I've been diving into Angular.js and exploring the resolve feature of the route provider to preload my Project data from a service before the page loads. Previously, I was fetching the data directly inside the controller. Howeve ...

Using AngularJS to bind models to a multidimensional array

As I am new to angular js, please bear with me. In my view, I have a grid of text input boxes that I would like to map to a 2D array in my controller or something similar in java script. The code in my view is as follows: <div ng-repeat="row in [1,2,3, ...

Exploring the meaning behind RxJS debounce principles

Referencing information found in this source: const debouncedInput = example.debounceTime(5); const subscribe = debouncedInput.subscribe(val => { console.log(`Debounced Input: ${val}`); }); When the first keyup event occurs, will the debouncedI ...

JavaScript: Locate web addresses within a block of text and convert them into clickable hyper

How can we convert the following PHP code to JavaScript in order to replace URL links inside text blobs with HTML links? A jsfiddle has been initiated. <?php // The Regular Expression filter $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a- ...

Passing arguments from an Angular directive to a controller function within an element's HTML

Is there a way to pass the URL of an anchor tag in the directive to the controller function "itemClicked"? The code below successfully logs the "post" object when clicked. HTML: <div ng-repeat="post in posts" > <div find-urls link-clicked="i ...

Having trouble selecting a default option in a dynamically populated select dropdown using ng-model in the dropdown

For my Angularjs application, I needed to dynamically return a select drop down with its selected option. To accomplish this, I implemented the following function: function getCellRendererMapping(data) { if (data.order == 6) { return funct ...

Is it possible to incorporate a combination of es5 and es2015 features in an AngularJS application?

In my workplace, we have a large AngularJS application written in ES5 that is scheduled for migration soon. Rather than jumping straight to a new JS framework like Angular 2+ or React, I am considering taking the first step by migrating the current app to ...

Retrieve a JSON file from the local file system using AngularJS

I recently started learning AngularJS and I am trying to read a JSON file from my local system. However, when I attempt to do so, I encounter an exception error that says: "Access to restricted URI denied XMLHttpRequest." Here is the code snippet: var de ...