AngularJS dynamic and wildcard routing strategy is a powerful feature that allows for flexible and customizable navigation within web applications

Currently, I have implemented angular ui router as shown below:

angular
  .module('app', [
    'ui.router'
  ])
  .config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
    $urlRouterProvider.otherwise('/');
    $stateProvider
      .state('start', {
        url: '/',
        templateUrl: 'templates/start.html',
        controller: 'startCtrl'
      })
      .state('dictionary', {
        url: '/dictionary',
        templateUrl: 'templates/dictionary.html',
        controller: 'dictionaryCtrl'
      })
  }])

Everything is functioning properly.

My next goal is to extend the URL structure starting from /dictionary.

The dictionary section will display a repeated list of li elements based on an array of objects fetched from a dynamic source.

<ul>
      <li ng-repeat="element in array">
          {{element}}
      </li>
</ul>

Upon clicking an element in the list, the controller should update the array and re-render the list with child elements related to that selected element from the source.

However, I am facing a challenge

Initially, I want the URL to show:

/dictionary/selectedelement

If I navigate back in the browser, I expect to return to

/dictionary

And if I were to bookmark

/dictionary/selectedelement

I would like to render the list based on that last segment of the URL.

If possible, I also prefer using the same controller for this functionality.

Answer №1

It seems like you have a scenario where you need to handle dynamic states with a shared controller.

For example,

/dictionary/my-first-element
/dictionary/my-second-element

Is that correct?

This is similar to what we do on our platform Wishtack.com for managing i18n urls.

We utilize a utility service with a method that creates states based on a configuration object.

In your case, it could be implemented like this using underscore.js:

stateList = _.map(stateConfigList, function (stateConfig) {
  return {
    controller: 'YourGenericController',
    name: stateConfig.name,
    url: '/dictionary/' + stateConfig.url,
    /* Additional fields can be added for different behaviors per state but still utilizing the same controller. */
    settings: stateConfig.settings
  }
});

angular.forEach(stateList, function (state) {
  $stateProvider.state(state.name, state);
});

Your controller can have unique functions based on the current state:

$scope.showCrazyStuff = $state.current.settings.showCrazyStuff;

Does this align with your requirements?

Regarding the back button behavior, you can manipulate the history using:

 $window.history.pushState()

However, overriding the browser's back button behavior may not provide an optimal user experience as it can lead to unexpected navigation changes.

In conclusion, dynamically adding and removing states during runtime while controllers are running might not be straightforward due to AngularJS routing limitations. It is recommended to define all possible states beforehand.

I hope this information proves helpful!

UPDATE:

An alternative approach would be to declare a single state like { url: '/dictionary/:itemId' } Then in your controller, access "$stateParams.itemId" to determine the specific element being viewed by the user.

The initial solution offers flexibility in assigning distinct controller/template pairs to groups of URLs.

At Wishtack, we also implement a technique for selecting different controllers based on the context:

.controller('Controller', function ($stateParams) {
  if ($stateParams...) {
     /* Using classes via dejavu, ControllerOne and ControllerTwo extend a base class ControllerBase. */
     return new ControllerOne();
  }
  else {
     return new ControllerTwo();
  }
});

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

Arranging objects in an array based on a separate array of strings

Here is an array of objects that I need to rearrange: var items = [ { key: 'address', value: '1234 Boxwood Lane' }, { key: 'nameAndTitle', value: 'Jane Doe, Manager' }, { key: 'contactEmail', value: ...

Sorting a parent array in AngularJS using a child array's Date field as the basis

I have an array of arrays of objects with the following structure: parentArray = [ [{id:1, date:1505020200000}, {id:4, date:1505020200000 }], [{id:2, date:1504681500000}], [{id:3, date:1504671000000}, {id:20, date:1504671000000}] ] Each nested array cont ...

What is the best way to transfer JSON data to a different controller in AngularJS?

Hello, I'm still learning AngularJS and facing an issue with the following code snippet. app.config(function($routeProvider) { $routeProvider .when('/', { templateUrl: "partials/home.html", controller: "mainControlle ...

Using AngularJS Material's mdDialog to show locally stored data in a template

In the controller, the section responsible for spawning mdDialog appears as follows: $scope.removeAttendee = function(item) { console.log(item); $mdDialog.show({ controller: DialogController, templateUrl: 'views/removeMsg.tm ...

Execute an Angular factory AJAX request with each change in route

I operate a factory where I utilize a function called getExpenseList that performs an ajax call to fetch data from the expense table. Currently, I have two routes set up - one for listing expenses and another for adding new expenses. However, whenever I n ...

Strip newline characters from information in AngularJS

What is the recommended approach for detecting and formatting the "\n\n" line breaks within text received from the server before displaying it? Check out this Fiddle: http://jsfiddle.net/nicktest2222/2vYBn/ $scope.data = [{ terms: 'You ...

Leveraging ng-selected in AngularJS to effortlessly select multiple options from a collection

Two arrays of objects are causing me some confusion, with one array being a subset of the other: $scope.taskGroups = [ {id: 1, name: 'group1', description: 'description1'}, {id: 2, name: 'group2', description: 'descr ...

The validation directive is run on each individual item within the ng-repeat loop

As I develop a single page application utilizing Angular and Breeze, the challenge of managing entities with dynamic validation arises. With a set of entities displayed on the page using data-ng-repeat, I implement in place validation through toggling betw ...

create a word with only **one** bold letter in the word ionic-angularjs

Can someone please guide me on how to style only a specific letter within a word using angularJS? Specifically, I want to make the first letter bold while keeping the rest of the word in normal font. For instance, if I have an array of words like: var Wor ...

Clicking to Load Images - Angular

Implementing a feature to load sets of images on button click instead of loading all at once. Although lazy load plugins are available, I decided to experiment with this approach. Here's the logic: Start with a data array called 'Images' co ...

Structural engineering for massive webpage

Currently I am in the process of building a large page using AngularJS. As I plan out the architecture for this page, I am debating which approach would be most effective. The page consists of 3 distinct blocks with various functionalities, but the prima ...

Error: Trying to access properties of an undefined object (specifically 'promise.data.map')

Currently, I am in the process of writing unit tests for a project built with Angular version 1.2. For my controller tests, I have set up a mockService that returns a deferred promise. One of the service methods looks like this: function getItems() { ...

Show the URL hash as url.com/something#/ rather than url.com/something/#/

I'm encountering a peculiar issue with my Angular v1.6.5 setup. My routes seem to be acting strangely, for example: $routeProvider .when('/', { templateUrl: 'myTemplate', controller: 'myController', method: &apo ...

Troubleshooting issues with AngularJS's minDate functionality

I have been trying to set the minDate for the datepicker to today, following the example on the angularJS bootstrap site. However, it seems like something is not working correctly. There are no console errors showing up, but it appears that the minDate is ...

Determine the total number of arrays present in the JSON data

I'm currently working on a straightforward AngularJS project, and here's the code I have so far: This is my view: <tr ng-repeat="metering in meterings"> <td>1</td> <td>{{metering.d.SerialNumber}}</td> ...

We were unable to load the resource because the server returned a 404 (Not Found) error. The EnterpriseMaster/BindNatureofAssignment feature is not functioning properly after being published

While the code is working perfectly fine on localhost, as soon as I publish it I encounter an error that prevents the table from loading. EnterpriseMaster/BindNatureofAssignment:1 Failed to load resource: the server responded with a status of 404 (Not ...

Unable to alter a global variable while iterating through an angular.forEach loop

I've encountered a challenge while attempting to modify a global variable within an Angular.forEach loop. Although I can successfully update the variable within the loop, I'm struggling to maintain those changes when accessing the variable outsi ...

Switching from AngularJS to vanilla JavaScript or integrating AngularJS and Flask on a single server

It is common knowledge that angular has the ability to create a project and convert it into pure HTML, CSS, and js code. Similarly, I am looking to do the same for my AngularJS application. When I execute the app using npm start it works perfectly fine. My ...

The route parameters seem to be malfunctioning when using the Google Maps Directions API

Currently, I am attempting to transfer the latitude and longitude of a location from one HTML file to another using the $routeParams feature. In the second HTML file, I utilized the Google Maps directions API to display the directions from the source lati ...

How to programmatically unselect an ng-checkbox in AngularJS when it is removed from an array

Utilizing checkboxes to gather values and store them in an array for dataset filtering purposes. The objectives are as follows: Show child filters when parent category is selected. Unselect all children if parent is unselected (otherwise they will ...