Enhancing User Experience in AngularJS UI-Router by Updating State without Refreshing the Template

I have noticed that every time I navigate to a different state, my templates and controllers are refreshing. This is not the behavior I want; I would like to retain the values entered into a form on contact.html when switching to home.html. Currently, I am working with Angular v1.6 & UI-Router v1+. Here is how my setup looks:

function() {
        "use strict";
        angular.module("App").config(["$stateProvider", "$urlRouterProvider", "$locationProvider", "$compileProvider", function(a, b, c, d) {
            c.html5Mode(false), c.hashPrefix(""), b.otherwise("/"), a.state("home", {
                url: "/",
                templateUrl: "views/home.html",
                controller: "HomeCtrl"
            }).state("projekte", {
                url: "/projekte",
                templateUrl: "views/projects.html",
                controller: "ProjectsCtrl"
            }).state("labor", {
                url: "/labor",
                templateUrl: "views/lab.html",
                controller: "LabCtrl"
            }).state("kontakt", {
                url: "/kontakt",
                templateUrl: "views/contact.html",
                controller: "ContactCtrl"
            })
            d.debugInfoEnabled(false);
        }])
    }.call(this),

This is the structure of my index.html:

<body ng-app="App">
   <main ui-view="">
           ..contact.html ..projects.html
  </main>
</body> 

The question I have is:

How can I switch between states without causing a refresh in my templates/controllers?

Answer №1

Why do you want to make that change? It's the default behavior and should be sufficient for your relatively simple requirement. Instead, consider saving the model value of the form by creating a service or factory, then load the form fields from that data during the initial load using dependency injection.

myApp.service('formDataService', function(){
  var formData;
  this.getData = function(){
    return formData;
  }
  this.setData = function(data){
    formData = data;
  }
});

Your controller code could look like this:

myApp.controller('ContactCtrl', function($scope, formDataService){
    var initialData = formDataService.getData();
    $scope.user = angular.copy(initialData);
    $scope.$watch('user', function(newVal, oldVal){
      formDataService.setData($scope.user);
    });
});

In this code snippet, $scope.user represents the model object for the form fields.

Check out the Plunker for more information.

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

Confirming the validity of an email address with Md-chips

Email Validation for MD-Chips Struggling with creating an email validation for md-chips. The current expression I'm using is not working as expected, since the ng-keypress directive is triggered every time I type something. Any suggestions on how to ...

AngularJS allows users to easily navigate between different web pages by using tabs

I have created this Angular JS code to display tabs that open specific URLs when clicked. Can someone please assist me with making the tabs functional? <html ng-app="blp_tabs"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angula ...

Guidelines for showcasing validation summary on an ASP.NET webpage with the help of Javascript

My asp.net form contains multiple required fields that need validation. I am looking to display a summary of all validations at the end of the form. Valid input controls have already been checked, now I just need the summary. Here is an example code s ...

Steps for formatting a date from the date object in the ng-model:

I am extracting date values using the ng-model directive in my controller. My goal is to display the date in the format 10-22-2013, however, it is currently showing up as 10/22/2013. How can I correctly format the date in this scenario? JavaScript : ang ...

Is there a way to modify an npm command script while it is running?

Within my package.json file, I currently have the following script: "scripts": { "test": "react-scripts test --watchAll=false" }, I am looking to modify this script command dynamically so it becomes: "test&qu ...

Having trouble displaying images in Express JS

Here are the lines of code that I wrote in Express: res.write("The current temperature is "+temp+". "); res.write("Weather is currently "+weatherDes); res.write("<img src=" +imageURL+ ">"); res.send() ...

Leveraging JSON in conjunction with AJAX and Python database operations

I am a beginner in Python and I am attempting to access the database through Python in order to retrieve results in a JSON array using AJAX. When I test it by returning a JSON list and triggering an alert in JavaScript, everything works fine. However, as ...

Having trouble getting Three JS to render files in scene 1 format 2?

Currently, I am working on an application that showcases 3D models imported from various modeling software. Specifically, I have an STL file exported from CatiaV5 and a DAE file exported from the latest version of Sketchup. Initially, I was able to succes ...

The v-show directive is not activated by a Vuex commit

I am experimenting with vuex for the first time, and I have come across an issue where a v-show directive is not triggering after a mutation commit on the store. // store.js import Vue from "vue" import Vuex from "vuex" const states = ...

Learn how to make a mesh in Three Js React refract its environment while keeping the background hidden from the camera

I've been grappling with this challenge for quite some time now, so any assistance would be highly valued! My aim is to create the illusion of an image being confined within a mesh structure. My initial idea was to utilize a mesh with defined thickne ...

It is my goal to populate the array with numbers while avoiding any duplicate entries

I am currently facing an issue with my code as it is returning a length of 0 instead of the expected result of 5 after excluding duplicates from the array. I have a feeling that there might be something missing in my code, but I just can't seem to fig ...

Refreshing UI components using a filter in Angular

I am currently working with a list that uses data-ng-repeat to display elements and filters based on the displayed items. <ul> <li data-ng-repeat="topic in topics | belongs:projectID"> <span>{{device.name}} </span><a d ...

Preserving state during navigation and router refresh in Next.js version 13

In the component below, we have a Server Component that fetches and renders data. When router.refresh() is called on click, it reruns the page and refetches the data. However, there is an issue with Nextjs preserving the state. Even though the server compo ...

Submitting with enter key on typeahead suggestions

Seeking guidance on Bootstrap typeahead: how can I configure it to submit the entered text upon pressing the enter key? Specifically, if I type "hello" in the typeahead input and hit enter, how can I submit "hello"? I've successfully disabled the aut ...

Sharing filtered data between controllers in AngularJS is a powerful feature to enhance data

One common topic of discussion is how to share data between controllers. In my case, I addressed this issue by creating a factory that contains functions for calling our API and retrieving the data we need. angular.factory('polygonService', [&ap ...

The timer will automatically refresh when the page is refreshed

Currently, I am encountering an issue while working on a quiz application in PHP. The problem arises when users start the test and the timer is running correctly. However, when users move to the second question, the timer resets again. Below is the code sn ...

Passing dynamic scope from Angular to a directive is a seamless process

I am working with a directive that retrieves an attribute value from an http call in the following manner: Controller app.controller("HomeController", function($scope){ $http.get("/api/source").then(function(res){ $scope.info = res.data }); }); ...

Launching a Node.js script with pm2 and implementing a delay

Utilizing the amazing pm2 package to maintain the longevity of my node.js applications has been extremely helpful. However, I have encountered a problem that I am unsure how to resolve. One of my applications involves multiple scripts, a server, and sever ...

Activate the parent navigation link when on sub-pages

I want to ensure that the parent navigation item is highlighted when a user is on a child page based on the URL. For example, if the user is currently viewing foo1-child and the parent is foo1, I need to apply the active class to Foo 1: http://foo.com/foo ...

Toggle visibility of a div with bootstrap checkbox - enforce input requirements only if checkbox is marked

Lately, I've been facing a strange issue with using a checkbox that collapses a hidden div by utilizing bootstrap. When I include the attribute data-toggle="collapse" in the checkbox input section, the div collapses but it mandates every single one o ...