Tips for preserving the value retrieved from a $http request when navigating back in the browser

In my application, I have a "search" button that retrieves an array of objects from a REST service. These values are then populated into a table using the ng-repeat directive. When a column is clicked, the page navigates to the next page with more details using the $routeProvider.

My query is: How can I retain the values in the table when the browser back button is clicked?

Below is my app.js code snippet:

myApp.config(['$routeProvider', function($routeProvider) {
    $routeProvider
    .when('/displayValues', {
        templateUrl: 'DisplayValues.html',
        controller: 'DisplayValuesController'
    })
    .when('/showDetails/:inputNumber', {
        templateUrl: 'ShowDetails.html',
        controller: 'DetailsController'
    })
    .otherwise({
        redirectTo: '/displayValues'
    });
}]);

Answer №1

Discover the role of the reloadOnSearch property in the $routeProvider. When set to false, modifications to querystring values will not prompt a reset of controllers, allowing them to maintain their current state (such as search results).

If you want the detail page navigation to occur via querystring, you must listen for changes using the $routeUpdate event. Refer to the $route documentation for more information.

Alternatively, you can store the search results in a service and reapply them when returning to the list page.

Answer №2

In AngularJs, saving state is done through services, which act as singletons and are accessible via dependency injection like all other components.

One way to achieve this is by creating a service like the following (note that this is just a basic example and not necessarily recommended practice):

angular.module('myApp', []).service('valueService', function() {
    var currentValues;

    return{
      setValues: function(newValues) {
        currentValues = newValues;
      },
      getValues: function() {
        return currentValues;
      }
    }
});

Initially, your controller can retrieve data from the service. If the value returned is undefined, you can make an XHR request to the server and then store the value in the service.

While additional logic and modifications may be required, the fundamental concept involves caching results in a service and fetching them from the controller when needed.

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 advantages do binary shifts offer in enums?

What do you think about this code snippet? /** * Bitmask of states */ export const enum ViewState { FirstCheck = 1 << 0, // result is 1 ChecksEnabled = 1 << 1, // result is 2 Errored = 1 << 2, // result is 4 ...

Storing data in a table created through a belongsToMany relationship in Sequelize and retrieving it. (Solution provided below)

My backend setup includes Node.js, Express.js, and Sequelize for database connections. I have established a many-to-many relationship between Tasks and Keys. I defined the connection between Tasks and Keys using Sequelize as follows: Backend // Task ...

Certain browsers have difficulty running CSS keyframes animations

As I work on my website, I have integrated a CSS keyframes animation that is triggered by clicking a link connected to a JavaScript function. Here is an excerpt from my CSS file: #banner { background-color: #00BBD2; position: absolute; width: 100%; heigh ...

Swap out a portion of HTML content with the value from an input using JavaScript

I am currently working on updating a section of the header based on user input from a text field. If a user enters their zip code, the message will dynamically change to: "GREAT NEWS! WE HAVE A LOCATION IN 12345". <h4>GREAT NEWS! WE HAVE A LOCATIO ...

Developing a unified input element containing numerous fields

After @grateful answered this question, I wanted to elaborate in case it could benefit others... In my project, there's a page called rsetup.php which has some PHP code to access a MySQL database for filling the HTML content of the page. This HTML ge ...

What is the best way to add a dropdown menu in front of a button?

I have a div containing a dropdown list of items and I want the user to be able to add more dropdown lists by clicking a button. Although I managed to do this, the issue I'm encountering is that the new list gets added after the button instead of ben ...

How to use addclass in AngularJS?

Can someone assist me with converting this to jQuery? $('.toggle').on('click', function() { $('.container').addClass('active'); }); $('.close').on('click', function() { $('.container&ap ...

Deactivate the Submit button when the database field has been populated

My form includes a submit button. The Submit button should be disabled if the "price" for a specific product is already filled: PHP Code <?php $host="localhost"; $username="root"; $password=""; $db_name="ge"; $con=mysqli_connect("$h ...

Understanding the process of sending data from a Cordova application to a PHP script and storing it in

I'm a beginner in cordova app development and I have a question about posting data from a form in a cordova application using PHP and MongoDB. I have my index.html file in the cordova app and comment.php in c:/xampp/htdocs. I want to display data from ...

Using AJAX and PHP to input data into the database repeatedly

Need help inserting multiple values into a database using Ajax and PHP. Currently, the code only inserts one value and I can't figure out why. PHP Code: $content = $_POST['content']; $text = $_POST['text']; mysql_query("inser ...

AngularJS and CSS: A Guide to Effortlessly Toggle Sliding List Elements

I am in the process of developing a drop-down menu that can be clicked. Using my custom AngularJS directive, I have successfully implemented functionality to load menu items dynamically. While I have made significant progress, I have encountered a small i ...

Error occurs in Windows script while running a project installed globally

Upon installing my project globally, I encountered a Windows Script Host error. https://i.stack.imgur.com/unFVu.png What steps can I take to resolve this issue? The following is my JavaScript code snippet: Object.defineProperty(exports, "__esModule ...

Tips for populating a dropdown list in Angular

I am encountering an issue with adding options to a dynamically created form. I have created a form based on dynamic data, but the select option is not being added as expected. What could be causing this problem? customerB : { rows:3, ...

What sets response.setHeader apart from response.writeHead?

When it comes to sending a JSON response from my Nodejs server in my application, I have discovered two different methods. However, I am unsure about the distinctions between them. The first method involves var json = JSON.stringify(result.rows); respons ...

Logic for calculating values inside a row that can be edited

Consider the following table structure: <tr class="data-row" ng-repeat="item in model.Invoice.InvoiceItemData"> <td> <input type="text" name="itemServiceTitle" ng-model="item.ServiceTitle" /> </td> ...

Is it possible to utilize jQuery to add 'a' attributes in HTML5?

Here is a snippet of code that works with Chrome and Firefox browsers: HTML: <a id="savefile""> Save transferred file </a> Javascript: // event is returned by a readAsDataURL() var save = document.getElementById('savefile'); s ...

"Encountering an 'Undefined function' error while implementing AJAX in the code

I'm encountering the issue Uncaught ReferenceError: GetLicenceUserList is not defined in the browser console when I utilize the function with $.ajax inside. However, the function works perfectly fine when I invoke it with just an alert("example& ...

Encountering difficulty when attempting to send a POST request to Strapi version 4.5.6 through a Next.js frontend, resulting in a 400

I am currently developing an events application using nextJS and strapi. I'm facing a problem when attempting to send a POST request to my local strapi server from nextJS on my localhost, resulting in a 400 Bad Request status. The request is targeted ...

Creating a Custom Hot Module Replacement Hook for Vue.js and Webpack

Is there a way to create a hook that triggers when a Vue component is updated using hot module replacement? [HMR] App is up to date. Now I want to execute a specific method after the update. ...

Cookies or Services: A Debate on the Best Practices for Storing Cart IDs

Technology Stack: React Node.js Choice 1: Upon receiving a request for "/", the server generates a cart in the database and saves the id in a cookie. Angular fetches the id from the cookie to use it in managing the cart. Whenever a purchase is made, t ...