How can we maintain data across states in UI Router without the need to pass them explicitly to $state.go(...)?

In the Gallery component, I have language code:

function Gallery(LanguageService) {
  var $ctrl = this;
  $ctrl.$onInit = function () {
     $ctrl.code = LanguageService.language;
     _loadGallery($ctrl.code);
  }
}

The LanguageService is a service that holds global language settings. For instance, codes like en for English and pl for Polish. When moving from the Gallery to the Image details component, the $onInit process remains the same - extract the code from the language and load data. The issue arises when adding image translations; for example, German translation with code de. This change affects the LanguageService, leading to mismatched languages:

  1. The Image displays in German
  2. Clicking on the Go back button redirects to the Gallery
  3. The Gallery lacks German translation results in a 404 Not Found error

One solution could be passing the galleryLanguage state to the Image:

$state.go("image.details", {id: image.id, galleryLanguage: $ctrl.language});

Yet, it's cumbersome without explicit definition in each image state; for example, transitioning from image.details to

image.edit</code requires:</p>

<pre><code>$state.go("image.edit", {id: image.id, galleryLanguage: $ctrl.language});
// To return to the gallery
function goBackToGallery() {
  $state.go(`gallery.details`, {galleryLanguage: $ctrl.galleryLanguage}); // then used in the Gallery if present
}

Alternatively, an additional service can handle this scenario:

function Gallery(LanguageService, TemporaryService) {
    var $ctrl = this;
    $ctrl.$onInit = function () {
      $ctrl.code = TemporaryService.language? TemporaryService.language : LanguageService.language;
      TemporaryService.language = undefined;
      _loadGallery($ctrl.code);
  }

  function goToImageDetails(image) {
    TemporaryService.language = String($ctrl.code);
    $state.go('image.details', {id: image.id});
  }
}

Perhaps Angular UI router offers a solution without custom implementation. Appreciate all assistance provided.

Answer №1

You can achieve this functionality using ui-route without parameters by following the example below:

Method one:

.state('eventListing', {
    url: '/events',
    templateUrl: 'views/eventListing.html',
    controller: 'eventListing',
    resolve: {
        categoryInfo: function() {
            return { id: 1 };
        }
    }
})

In the controller, you can access it like this:

app.controller('eventListing', ['$scope', 'categoryInfo',
    function ($scope, categoryInfo) {
        $scope.categoryId = parseInt(categoryInfo.id);
    }
]);

Reference: ui-router Resolving

Method two:

In this method, you do not need to use resolve. Simply pass an object with a data key in the ui-router state and access it in the controller using $state.current.data. See the example below:

.state('eventListing', {
    url: '/events',
    templateUrl: 'views/eventListing.html',
    controller: 'eventListing',
    data: {
        id: 1
    }
})

In the controller, you can access it like this:

app.controller('eventListing', ['$scope', '$state',
    function ($scope, $state) {
        $scope.categoryId = parseInt($state.current.data.id);
    }
]);

Answer №2

1- Utilize the params option within your route configuration

.state('about', {
        url: '/about?isDraft',
        params: {
         isDraft: null
        }
      })

2- Implement services as mentioned

3- Save your data in sessionStorage

These are the choices I recommend.

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

Is it advisable to use Angular $resource JSON Callback if it's not functioning correctly?

I am in the process of creating a resource to send data to my controller for an existing API that I need to connect with. Unfortunately, I do not have the ability to make any changes on the backend. Current state of my Resource factory: 'use strict& ...

Removing an item from an ng-repeat loop while also dealing with a FormController within

I am encountering a significant issue with form inputs nested within the ng-repeat directive. I require an input that is an array and can vary in size; allowing users to add or remove parts of the form. Within the ng-repeat directive, there is an ng-form ...

Different ways to attach or cycle through various background images with text

I have a collection of images stored in a folder, and I am looking to randomly select one of the images to display as a full background image while also showing the text description related to that specific image. Here is the code snippet for achieving t ...

Obtaining user data for an authenticated user with SpringSecurity and AngularJS is a crucial aspect of developing

I am currently using a certain method to log users into my application, but I want to switch to an angular function for the login process. In order to do this, I would like to create a restful web service for authentication. However, all the examples I hav ...

Restrict the number of rows displayed in the ui-grid to the maximum

I'm looking to adjust the height of the ui-grid so that it fits the size of 3 rows. After reviewing the ui-grid documentation, I noticed that there is a minRowsToShow property available, but couldn't find an equivalent for maxRowsToShow. I' ...

Methods for minimizing components re-rendering

I'm currently exploring Next.js. I have two pages, A and B, each containing component C. Whenever I navigate between the pages, component C gets re-rendered. Is there a way to prevent this from happening? To clarify, I don't want useEffect to exe ...

Can you explain the distinctions between $document and $window for me?

My query revolves around AngularJS as I am in the process of creating directives. Specifically, I am looking to understand the distinctions between $document and $window. This knowledge is crucial for me because the directives I am working on need to ada ...

Getting the value of dynamically generated buttons when they are clicked in PHP - a simple guide

In my PHP code, I have successfully created dynamic buttons. However, I am facing an issue where I need to retrieve the value of a specific button when it is clicked, and populate all the information in a form. Below is the code snippet for handling the b ...

Navigating through jQuery and straightforward code?

Before I pose my question, let me clarify my objective: I aim to write code with maximum efficiency while still incorporating extensive functionality. In my eyes and those of my colleagues, this is what we refer to as 'beautiful code'. The issue ...

Error in TMDb API: JSON data abruptly ended

Currently, I am attempting to parse JSON data that is being returned by The Movie DB. Unfortunately, I keep encountering an error message indicating the following: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) ...

Strategies for handling TypeScript's treatment of uninitialized optional parameters as non-undefined values

Here is a simplified version of my function: const nullify = <T extends string | undefined>( value?: T, ): T extends string ? string : null => { if (value === undefined) return null as any; return value as any; }; I expected this function t ...

Angular and UI Router - the template seems to be loading, however, there is no content displayed on the document

I am currently utilizing Angular 1 in conjunction with UI Router(https://github.com/angular-ui/ui-router). This is how my primary app.js file appears: var myApp= angular.module('myApp', [ 'ui.router' ]); myApp.config(function($s ...

Is there an error when trying to show text and images using an HTML model after clicking a button?

How can I modify this code to have multiple buttons, each displaying a different modal when clicked? The current code only works for a single button and modal. <!DOCTYPE html> <html> <head> <meta ...

What could be causing the issue with my hour parameter in node-cron?

Having difficulty setting up a cron job to run with node-cron every Monday at 8:30. I've tried using "30 8 * * Mon" and even "30 08 * * Mon", but it doesn't seem to work. Interestingly, "30 * * * Mon" does work and runs every hour on the 30th min ...

Is there a way to generate a distinctive curved design using CSS for a

I am currently using CSS and div elements in an attempt to create these particular lines: https://i.stack.imgur.com/Ytowq.png .line { width: 1px; height: 100px; background-color: black; position: absolute; border-radius: 50%/100px 1 ...

Using jQuery to create a flawless animation

I am currently working on an animation project, and I have shared my progress on jsfiddle. Below is the code snippet I have utilized: /* JavaScript: */ var app = function () { var self = this; var allBoxes = $('.box&apos ...

Show the image on top of the div block as the AJAX content loads

Implementing this task may seem easy and common, but I am struggling to figure it out! What should take five minutes has turned into an hour of frustration. Please lend me your expertise in getting this done. I have a div container block: <div cla ...

Tips for converting .WAV files to .MP3 format and streaming audio within a Meteor application

I have a function in my Meteor app that retrieves .wav data based on a text input. I now want to convert this .wav data into .mp3 format and play the audio within my app. How can I accomplish this? Meteor.call("watsonaudio",wusername,wpassword,text, funct ...

Angular is attempting to access a function that has not been utilized within the return object of the directive

Below is the directive I am currently using: 'use strict'; angular.module('App') .directive('aView', function ($stateParams) { this.link = function(scope, template, directiveAttrs){ template.addClass(scope.elem.c ...

When an anchor link is dynamically created, the `click()` method does not activate the click event

After creating an anchor element using the document.createElement('a') method, I encountered an issue where the click event was not being triggered as expected. To provide more context, refer to the code snippet below: var link = document.create ...