What is the method for transferring form data to a different page?

Currently utilizing AngularJS version 1.5.6 and looking for guidance on properly passing form data using $location.path.

Below is my code snippet for Page A:

<form>
...
    <button type="submit" ng-click="submit(formData)">submit</button>
</form>

JavaScript code:

app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
// Home
.when("/", {
  templateUrl: "A.html", 
  controller: "ACtrl"
})
.when("/B/", {
  templateUrl: "B.html", 
  controller: "BCtrl"
})
  //fallback url if nothing matches
.otherwise({
  redirectTo: '/'
}); 
}]); 
app.controller('ACtrl', function ( $scope, $location, $http) {
$scope.formData = {};
$scope.submit = function() {
    $location.path("/B/" + $scope.formData );
};
});
//controller for B page
app.controller('BCtrl', ['$scope', '$routeParams',
function($scope,$routeParams) {

$scope.formData = $routeParams.formData;
}]);

This example may seem straightforward, but I'm struggling to find a solution :(

When clicking submit, nothing happens. If I remove the $scope from $scope.formData, I receive an error stating "Error: formData is not defined."

The values in formData are accessible, as confirmed by testing with console.log($scope.formData).

Here is the link to the Plunker: https://plnkr.co/edit/K5zwcmRRyom5HR4a5Q9o

EDIT

The only remaining issue is how to correctly handle the select object in the foreach loop. Assistance would be greatly appreciated.

Answer №1

To achieve this, one method is to create a service and utilize setter/getter functions for transferring a variable. Here's an example implementation: https://plnkr.co/edit/IuTXsVLU7dq3TylfnSYP?p=preview

app.service('TransferService', [function(){

 var savedData,
 service = {
   getData: getData,
   setData: setData
 }

 function getData(){
   return savedData
 }

 function setData(data){
   savedData = data
 }

 return service
}])

Answer №2

Avoid using location.path...

You have the option to utilize a service or leverage browser storage such as localstorage, sessionStorage, or indexdb.

Service Method Provided Below

app.service("SomeService", function () {

    var value = null;

    this.set = function (val) {
        value = val;
        return this;
    }

    this.get = function () {
        return value;
    } 
})

app.controller("ACtrl", function ($scope, SomeService) {

    $scope.formData = {};
    $scope.submit = function() {

        //If you've inputted data...
        SomeService.set($scope.formData);

        $location.path("/B/");
    };

})

app.controller("BCtrl", function ($scope, SomeService) {

    $scope.formData;

    (function () {

        //Checking if the data is stored in the SomeService service.
        var dataFromACtrl = SomeService.get();
        if (dataFromACtrl) {
            $scope.formData = dataFromACtrl;
        }
    })();
})

Using localStrorage below, can also use sessionStorage.

app.controller("ACtrl", function ($scope, SomeService) {

    $scope.formData = {};
    $scope.submit = function() {

        //If you've populated it with some data...
        window.localStorage.setItem("form_data", JSON.stringify($scope.form_data));
        $location.path("/B/");
    };

})

app.controller("BCtrl", function ($scope, SomeService) {

    $scope.formData;

    (function () {
        var dataFromACtrl = window.localStorage.getItem("form_data");
        if (dataFromACtrl) {
            $scope.formData = JSON.parse(dataFromACtrl);
        }
    })();
})

Note:

If using the localStorage example, remember to clean up after using the data in Bctrl by removing the entry from localstorage with either of the following lines of code:

window.localStorage.removeItem("form_data");

delete window.localStorage["form_data"];

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

Sending JavaScript functions to PHP files via Ajax

My Current Project: I am currently developing a script that provides users with choices and generates new options based on their selections. To achieve this, I have created two scripts - one for the HTML structure of my page and another for fetching serve ...

Node.js accepts JSON data sent via XMLHttpRequest

I have successfully implemented a post method using xmlhttprequest: var xhttp = new XMLHttpRequest() xhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { console.log('Request finished. Pro ...

Visual Studio Code's Intellisense is capable of detecting overloaded functions in JavaScript

What is the best way to create a JavaScript overload function that can be recognized by Visual Studio Code IntelliSense, and how can this be properly documented? A good example to reference is Jasmine's it() function shown below: function it(expecta ...

What could be the reason for the Mongoose findAll function causing a 500 error to occur?

My model / Schema has a working create method, but the "all" method is causing a 500 error. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var DiSchema = new mongoose.Schema({ name: { type: String, lowercase: true , require ...

Guide to iterating through an array within an object in Vue.js

Can someone help me with looping through data fetched from an API using a GET request in Vue.js? This is the sample response obtained: "data": { "Orders": [ { "OrderID": 1, "Ordered_Products": { ...

Comparing a series of smaller strings to a larger string for testing purposes

My website has an array filled with bot names. Whenever a user or bot visits the site, I retrieve the user-agent and want to check if any of the values in my array are present in it. var bots = [ "twitterbot", "linkedinbot", "facebookexternalhit", ...

Having difficulty initializing jQuery DataTables upon button click with an Ajax request

I have a piece of HTML code that represents a partial view: <table id="table_id" class="table table-inverse"> <thead class="thead-inverse"> <tr> <th>Select</th> ...

New to Angular: Getting Started with NgModel Binding

Novice query: I am facing an issue with a simple input type=text element linked to ng-model="xyz.zyx", where xyz refers to an object. In my controller, I initialize this object and set the value for the property zyx as shown below: xyz { zyx: $scope.zz ...

Having trouble getting the Google motion chart to work with asynchronous JSON requests

I have been using the code below to make a request for a JSON file and then parsing it. google.load('visualization', '1', {packages: ['controls', "motionchart", "table"]}); google.setOnLoadCallback(function(){ createTable($(& ...

The pie chart is unable to render due to issues with accessing the external JSON file in Ext

I attempted to create a pie-chart using extjs, but unfortunately, the pie-chart is not showing up. Interestingly, when I pass the JSON data through AJAX inline, it works perfectly fine. However, when I try passing it through a file, it doesn't work a ...

The response time feature appears to be malfunctioning within Mockjax

How can I simulate a long response time using Mockjax? Despite setting the responseTime to 20 seconds, my ajax call is still being executed immediately when the page loads. Any suggestions on how to fix this issue? To isolate potential sources of error, ...

How to make an entire video clickable on Android for seamless playback?

I have implemented an HTML5 video in my mobile web application. Currently, users need to click the small play icon at the bottom left of the video to start playing it. Is there a way to make the entire video clickable so it plays when clicked anywhere on t ...

Add one string to an existing array

I have a component named ContactUpdater that appears in a dialog window. This component is responsible for displaying the injected object and executing a PUT operation on that injected object. The code for the component is shown below: HTML <form [for ...

What is the best way to modify the styling of my CSS attributes?

I'm currently working with this CSS code: input:checked + .selectablelabel .check { visibility: hidden; } Now, I want to change the visibility property to "visible" using JavaScript. I attempted the following: $(document).on('click', & ...

Guide on how to add multiple options to a select element in HTML using prototype.js

What is the best way to add multiple options to a select tag in HTML using prototype js? Appreciate your help. ...

Is it possible to use multiple schemas for one collection name?

I am currently working on creating different schemas for a single collection, such as User or subUser. I aim to store both User and subuser data in the same collection but with different schemas. Here is an example of my schema file: export const AryaSchem ...

NGRX Store: Unable to modify the immutable property '18' of the object '[object Array]'

While attempting to set up an ngrx store, I encountered 7 errors. Error Messages: TypeError: Cannot assign to read only property '18' of object '[object Array]' | TypeError: Cannot assign to read only property 'incompleteFirstPass ...

Move to the following <article>

I am currently working on developing a JavaScript function that will automatically scroll to the next article whenever the down arrow key is pressed. The challenge I am facing is that my HTML elements are all dynamic and are simply article tags without any ...

The $http.then callback is failing to be executed

I am encountering an issue with a $http.post call where the callback function is not getting called. Surprisingly, I have another call with identical code that works perfectly fine. Can anyone spot any problems in the code snippet below? var data = {entit ...

Dynamic shopping cart with Vue.js

Currently, I am working on a shopping cart project using Vue.js and Vuetify. I need help figuring out how to capture the boolean value true or false and adjust the total price in the amount based on whether it is true or false. Any suggestions? <v-con ...