In JavaScript, you can easily save the previous stage by using the go() method with a

For my current project, I have implemented the use of angular $routeProvider for page navigation. To navigate back, I am using javascript.go(-1). However, a problem arises when clicking the back button as it reloads and re-renders all the data. Is there a way to retain the previous state when using javascript.go(-1)?

app.config(function ($routeProvider, localStorageServiceProvider) {

    $routeProvider
        .when('/api/lecturer/', {
            templateUrl: 'partials/dashboard.html',
            controller: 'dashboardController'
        })
        .when('/account/lecturer/project/', {
            templateUrl: 'part/lecturer_project.html',
            controller: 'projectController'
        }).otherwise({redirectTo: '/login'});})

HTML:

<li>
      <a onclick="javascript:history.go(-1);" style="cursor:pointer;" class="button">back
            <i class="entypo-left-dir right"></i>
      </a>
</li>

Answer №1

In order to implement a simple solution, you can store the previous page in a service or factory and access it in your controllers. Below is a quick example using ngRoute:

var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
  $routeProvider
    .when('/', {
      templateUrl: "main.html"
    })
    .when('/api/lecturer/', {
      templateUrl: 'partials/dashboard.html',
      controller: 'dashboardController'
    })
    .when('/account/lecturer/project/', {
      templateUrl: 'part/lecturer_project.html',
      controller: 'projectController'
    })
    .otherwise({
      redirectTo: '/'
    })
});
app.controller('dashboardController', function($scope, historyService) {
  $scope.back = historyService.get();
});
app.controller('projectController', function($scope, historyService) {
  $scope.back = historyService.get();
});

app.service('historyService', function() {
  /*  `this.back` can be an array instead, 
    which will work as a stack, 
        pushing new previous pages
        and popping then when redirected back
  */
  this.back = "";
  this.get = function() {
    return this.back;
  }
  this.set = function(val) {
    this.back = val;
  }
  this.delete = function() {
    this.back = "";
  }
})

app.run(function($rootScope, historyService) {
  // `$locationChangeStart` event works better for this example
  $rootScope.$on("$locationChangeStart", function(event, next, prev) {
    //console.log(event); 
    //console.log(next); // current page
    //console.log(prev); // previous page
    historyService.set(prev); // store the previous page in a service
  });
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>

<body ng-app="myApp">

  <a href="#!/api/lecturer/">lecturer</a>
  <a href="#!/account/lecturer/project/">project</a>
  <hr>
  <div ng-view></div>

  <script type="text/ng-template" id="main.html">
    <p>main.html</p>
  </script>
  <script type="text/ng-template" id="partials/dashboard.html">
    <p>partials/dashboard.html</p>
    <a ng-href="#!/">Main</a>
    <a ng-href="{{back}}">Go back</a>
  </script>
  <script type="text/ng-template" id="part/lecturer_project.html">
    <p>part/lecturer_project.html</p>
    <a ng-href="#!/">Main</a>
    <a ng-href="{{back}}">Go back</a>
  </script>

</body>
</html>

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 pass the "$user" variable in a loadable file using ajax?

Is there a way to send the variable user to the mLoad.php file before executing this script? Any suggestions would be greatly appreciated. Thank you! $(document).ready(function(){ $("#message_area").load('mLoad.php'); $("#userArea").submit(func ...

Identifying DNS lookup errors in JavaScript: A beginner's guide

Is there a method to identify DNS lookup errors through JavaScript? Are there any code snippets or techniques that can achieve this? Is it a challenging task or is there a solution available? If anyone can provide some insight on this, I would greatly a ...

What steps can be taken to avoid a component from re-rendering (or maintaining its state unchanged) during page transitions?

Is there a way to prevent a shared component, like a sidebar, from re-rendering when transitioning between two pages? Specifically, if the sidebar is fixed at a certain y position in the scroll track, how can we ensure that it remains unchanged when navig ...

The active tabs or placeholders do not update properly when I click on them

Is there anyone who can help figure out why the tabs are not functioning as expected? The goal is for the tabs to change the input field placeholder and perform a search based on the active tab. If you're able to assist, please review my complete cod ...

What is the best way to dynamically add a stylesheet using JavaScript/jQuery?

I've been scouring the web for a solution to a particular issue, but so far I'm coming up empty-handed. We're working with Umbraco CMS for a client's website, and it seems we can't insert conditional comments in the <head> se ...

The challenge of maintaining consistency in Vue 3 when it comes to communication between

Context In my Vue 3 application, there is a HomeView component that contains the following template structure: <InputsComponent></InputsComponent> <CheckboxesComponent></CheckboxesComponent> <Toolbar></Toolbar> T ...

Guide to displaying the output of a JS calculation in a Bootstrap modal dialog box

I have a HTML and JavaScript code that determines the ideal surfboard for the user based on their input data (style, experience, height, weight) and displays the recommended surfboard type. Here is the initial code snippet I attempted to use: function c ...

Ways to gradually reveal all elements within a header section

Is there a way to gradually reveal all the components in my header once the window has finished loading by utilizing jQuery's fadeIn function? Below is the pertinent code snippet: HTML <div class="banner"> <header class="header"> < ...

A Step-by-Step Guide on Importing Components in Vue.js

I have defined the following component as shown below: import Vue from 'vue'; import Datepicker from 'vuejs-datepicker'; Vue.component('DatePicker', { template: ` <datepicker name="date"></datepicker> ` ...

"Enhancing Your Website with JavaScript File Uploading

I have been searching through various resources but couldn't find any relevant answers to my inquiry. The issue at hand is: When I attempt to post an image, the name appears as NULL which prevents the image from being uploaded. :/ Here is my ajax p ...

Aligning text vertically to the top with material UI and the TextField component

Seeking guidance on adjusting vertical alignment of text in <TextField /> const styles = theme => ({ height: { height: '20rem', }, }); class Foo extends React.component { ... <TextField InputProps={{ classes: ...

Click to trigger image rotation with JavaScript

img { display: block; margin: 20px; width: 50px; height: 50px; } .crossRotate { -webkit-transition-duration: 1s; -moz-transition-duration: 1s; -o-transition-duration: 1s; transition-duration: 1s; -webkit-transition-property: -webkit-tran ...

`How to prevent Query parameters from being lost upon reloading in Nextjs Router while maintaining a clean URL structure?`

My challenge lies in sending data via router.push to a page with dynamic room id (src/pages/editor/[roomid].tsx) in Next.js. I want the URL to stay clean so users can easily edit their username in the URL if needed. When initially loaded, router.query suc ...

Transferring information from View to Action

How can data be sent from the view to the controller? This is the select element where the data is retrieved (sel1): <div class="form-group" style="margin: 0 auto;"> <label for="sel1">Select a cat breed:</label> ...

The issue of bidirectional binding not functioning properly has been identified in AngularJS version 1.x

I have a directive that I want to make accessible across multiple pages. The requirement is that when any key is held down, the password should be displayed. The password details are passed from the controller and need to be updated in the directive. For ...

Allow the <a> tag to open separate URLs on different pages

My goal was to have the <a> tag open two URLs simultaneously. I tried the following: Using only HTML <a href="URL1" target="_blank" onclick="window.open('URL2');">text</a> While this method did wo ...

What could be causing my dropdown menu to not appear when clicked?

I am trying to implement the functionality shown in the image. When the Settings button is clicked, a window should open allowing the user to navigate to their desired option. However, I am facing an issue where nothing happens when the button is clicked. ...

Connecting an anchor link within a primary table to a secondary table by utilizing its unique identifier

I am looking to display a table of customers at the top of a page, each customer with a button in the last column. When a user clicks on the button, I want to show/hide a detailed table below the customer table. The data is readily available when the page ...

What is the technique for incorporating FontAwesome icons onto an HTML 5 canvas?

I am encountering an issue while trying to use FontAwesome icons within my HTML 5 canvas. Here is what I have attempted: ct.fillStyle = "black"; ct.font = "20px Font Awesome"; ct.textAlign = "center"; var h = 'F1E2'; ct.fillText(String.fromCha ...

Unlocking Global Opportunities with Stencil for Internationalization

Hi there, I've been attempting to implement Internationalization in my stencil project but unfortunately, it's not working as expected. I'm not sure what's causing the issue, and all I'm seeing is a 404 error. I followed these arti ...