Retrieve data from previous page without triggering a reload using AngularJS

Custom Routes :

app.config(['$routeProvider', function ($routeProvider) {
          $routeProvider

            .when("/home/:page", {templateUrl: "templates/home.html", controller: "HomeController"})

            .otherwise("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"});
        }]);

Controller :

     App.controller('HomeController', function ( $scope, $location, $http,defaultVal,$routeParams ,basic,State) {
    $scope.allList = State.formData;
    start = $routeParams.page == undefined ? 1 : $routeParams.page;
    var trip_data = {
        start:(Number(start)-1) * (Number(defaultVal.perPage)),
        perpage:defaultVal.perPage
    }
    basic.hitAPI(defaultVal.sitePath+"search",{reqObject:JSON.stringify(trip_data)}).success(function(response){
        if(response.type == "success"){
            p = Number(start)- Number(1) < 0 ? false : Number(start)-Number(1);
            result = Math.ceil(response.total / defaultVal.perPage);
            n = Number(start) + Number(1) > result ? false : Number(start) + Number(1);
            response.page = {
                next : n,
                prev: p
            };
            $scope.allList = response;
            State.formData = $scope.allList;
        } else if(response.type == "error"){
            basic.messages.showErrorMessage(response.message);
        }else{
            basic.messages.generalError();
        }
    });
});

HTML Template :

<div class="trips" >
    <div class="tripBox" ng-repeat="Home in allList.data" 
         ng-swipe-left="swipeLeft('/home/{{allList.page.next}}')"
         ng-swipe-right="swipeRight('/home/{{allList.page.prev}}')">
        <a ng-href="#/trip/{{Home.id}}">
        <h3>{{ Home.FromAddress }}  <i class="fa fa-long-arrow-right"></i> {{ Home.ToAddress }}</h3>
        <div class="poolPrice">${{ Home.charges }}</div>
        <p><span>Posted By :</span> {{ Home.UserName }}, 24 yrs, {{ Home.UserGender | capitalize }}</p>

    </div>
</div>

Issue arises when navigating back where a server request is sent for data retrieval. A solution is sought to display previous data without fetching from the server upon returning.

Answer №1

Alright, imagine you navigate back to a previous view and it needs to be re-rendered (regardless if it's the home page or another). If the controller of this page triggers a service call unconditionally, then it will definitely fetch the data again (I believe Angular prevents caching of its pages). It seems like you're using some form of state storage ($scope.allList = State.formData;), right? In that case, you can store the necessary data for the page and in the controller, check if it already exists before making an API call. However, keep in mind that this approach may result in outdated information on your page over time.

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

"Exploring the Power of VueJS Classes and Conditions

Is it possible to add a Class based on a Child's Class Condition in the menu? For example: <ul :class="{ 'open' : ThereIsClassInChild }"> <li v-for="item in list" :class="{ 'active' : $route.name == item.routeName }" ...

Having trouble with the Mysqli query not functioning properly in PHP code after being dispatched via Ajax

I am encountering a problem with a specific Myqsli query. $sqlselect = "SELECT visitatori_id FROM visitatori WHERE visitatori_nome='".$nome."' AND visitatori_cognome='".$cognome."' AND visitatori_orastart='".$time."' AND v ...

JavaScript's square bracket notation is commonly used to access nested objects within an object

My goal is to accomplish the following: this.inputs[options.el.find('form').attr('class')] = {}; this.inputs[options.el.find('form').attr('class')][options.elements[x].selector] = false; Unfortunately, I'm fa ...

Using Javascript to fetch undefined data from a C# backend with AJAX

I am struggling to create a web page using Google charts. I attempted to build it with C# as a web form and retrieve data from a local database to JavaScript. However, I keep receiving an error stating that the data is undefined in the response from Ajax. ...

inserting a for-loop inside a div tag

I've created a script that modifies the background color and plays a sound in response to user input. The changes are triggered by the length of the input provided. Additionally, I have a div element where I aim to display the specific letter causing ...

Introducing errors into a form manually

Is there a way to intentionally introduce an error into a form manually? I am familiar with doing it via a directive, but unsure of how to inject an error from the controller. <div ng-controller="myController"> <form name="createForm"> ...

Troubleshooting the Thumbs-Up and Thumbs-Down Voting System

My objective is to display multiple images on a single webpage and allow the general public to vote on them. I have implemented an AJAX command to hide the voting buttons and show a "thank you for your vote" message. This functionality works perfectly when ...

Effectively detect the 'scrollend' event on mobile devices

When implementing the -webkit-overflow-scrolling: touch; style on a mobile element, dealing with scroll events can be quite challenging as they are triggered by various actions such as 'flicking', 'panning' and when the scroll comes to ...

Running 'Grunt Serve' is successful, but encountering issues with 'Grunt Build/Upload' when working on a static site

I'm encountering an issue with a Grunt build that I put together. The Challenge Everything runs smoothly locally when I execute grunt serve. However, after running grunt build and syncing the content to my S3 bucket, the ng-view pages don't ren ...

Converting a floating point number to a 4-byte hex string in JavaScript and reversing the process

I have received a hexadecimal data from the server side that is supposed to be in float format. I am trying to convert these hexadecimals into floats using JavaScript, but so far I have been unable to find a suitable method. Can anyone provide assistance ...

Having trouble updating values in Vue3 when accessing the next item in an object?

I'm attempting to allow my users to browse through a collection of various items. Take a look at the records object below: 0: {id: 1, pipeline_id: 1, raw: '1', completion: null, processed: 0, …} 1: {id: 2, pipeline_id: 1, raw: '2&apo ...

Passing a variable from a service to a controller in AngularJS

I recently developed a basic app that includes user authentication based on the guidelines found in this useful resource. The core components of my app are a userAccountService, which manages communication with the server, and a login controller that over ...

Using the Angular leaflet-directive alongside the $routeProvider for seamless integration

I am trying to incorporate the leaflet plugin into my Angular JS project. After discovering this directive on https://github.com/tombatossals/angular-leaflet-directive and following the official Angular tutorial, I attempted to create a code using ngview a ...

When utilizing Md-select in Protractor, how can the dropdown list be accessed?

I am having trouble locating the option from the dropdown menu that I need to select. Despite trying various methods, I have not been successful. <md-select ng-model="card.type" name="type" aria-label="Select card type" ng-change="$ctrl.onCardSelecti ...

The value of a variable undergoes a transformation following its insertion into an

During my coding tests, I came across this snippet of code: <script> var newData = {}, graphs = [] for(var j=0; j<2; j++){ newData["name"] = 'value '+ j console.log(newData["name"]); graphs.push(newData); console.log ...

Tips for integrating ons-sliding-menu into ons-navigator using Angular ui-router?

I'm having trouble loading ons-sliding-menu inside the ons-navigator using angular ui-router. Can someone please take a look at my code below and let me know what I'm doing wrong? I'm not getting any errors in the console, but it's just ...

Increase or decrease values by clicking on Material UI IconButton

Looking to incorporate the functionality of an onClick() event for a Material UI IconButton that can either increase or decrease the Calories value for each item in the table. I've referenced the code from the Table React component page. https://i.ss ...

Incorporate a new item into an array within a JSON `document` using Node.js for every incoming request

I'm facing an issue with storing multiple sets of x, y coordinates in a file on the server side. Currently, when a user right clicks on an image on the frontend, the coordinates are sent to the node server via AJAX post request and saved as objects in ...

Angular is throwing an error stating that the type '{ }[]' cannot be assigned to the type '[{ }]'

I'm in need of assistance and clarification regarding the error I encountered in my application... When I receive a JSON response from an API with some data that includes an array of products, I aim to extract these products (izdelki) from the array, ...

Master the art of animating ng-view transitions with AngularJS

I have 2 distinct HTML pages, namely welcome.html and login.html. These two pages are incorporated or "inserted" into a common page called index.html through the utilization of an exclusive attribute known as ngview, together with a router provider. This i ...