Storing form information within the view

What is the best way to transfer data between views in AngularJS?

I tried using $rootScope but it's not working as expected.

Answer №1

It appears that you are using 2 different controllers for each view (or one for the view and none for the root view).

The issue here is that Angular cannot share data between controllers in this way.

To resolve this, you can either utilize a service/factory or use rootscope, but not in the manner you have done so. You should use broadcast and emit.

If I were in your position, I would opt for using a service.

UPDATE Here's a service for you:

(function() {
'use strict';
angular
    .module('YourModuleName')
    .factory('CountriesService', CountriesService);
CountriesService.$inject = ['Your', 'dependencies', 'here', 'in', 'string'];
/* @ngInject */
function CountriesService(your, dependencies, here, not, in, string) {

    var service = {
        setCountries: setCountries,
        getCountries: getCountries
    };

    var vm = this;
    vm.countries = []; // Or perhaps an object?
    // ... List of other variables you need to store.

    return service;
    ////////////////
    function setCountries(listOfCountries) {
        vm.countries = listOfCountries;
    }

    function getCountries() {
        return vm.countries;
    }
}
})();

This will help you store your variables. In your controller, you can add CountriesService as a dependency. To save, use CountriesService.setCountries, and to retrieve, use CountriesService.getCountries. Keep in mind that refreshing the page will erase all the data!

SECOND UPDATE If you're following John Papa's guidelines, here is a simple service you can implement in the same file where your controller is located:

    app.factory('CountryControl', function(your, dependencies) {

        var service = {
            setCountries: setCountries,
            getCountries: getCountries
        };

        this.countries = []; // Or maybe an object?
        // ... List of other variables you need to store.

        return service;
        ////////////////
        function setCountries(listOfCountries) {
            this.countries = listOfCountries;
        }

        function getCountries() {
            return this.countries;
        }
    });

Answer №2

In my experience, I have developed an application that handles this task with ease. By utilizing a service, you can effectively address the issue and also set up a system that allows for flexibility throughout your app.

Instead of relying on scope to manage this process, it is advisable to place an object on your controller (such as myFormObj) and assign the desired properties to it (e.g., name, rank, serial number).

Subsequently, establish bindings between the input fields of the form and the properties within that object, rather than using scope variables. This means that your ng-model references would appear as myCtl.formObj.name, and so forth.

Upon triggering the event that alters the view, make a duplicate copy of the formObj using angular.copy and store it in a separate location, typically within a Service (consider naming it FormStateService or similar). This service might simply maintain a basic array.

this.forms = { 'TheNameOfYourForm' : theFormObjToSave };

Thus, when the user activates the event that exits the form, you would execute:

formStateSvc.forms [ 'NameOfMyForm' ] = angular.copy ( theFormObj );

Upon the return of the user to the initial view and the re-initialization of the controller, you could inquire with the formStateSvc:

if ( 'NameOfMyForm' in formStateSvc.forms ) {
   this.formObj = formStateSvc.forms [ 'NameOfMyForm' ];
}

As a result, the previous form's state is successfully restored.

To enhance robustness, you could implement methods like "addForm" and "removeForm," handle scenarios involving undefined values, and streamline the rebind process to the former state (simply instructing your form's controller to restore the state if applicable during initialization). Consequently, your controller might feature:

this.formObj = formStateSvc.rebindOldDataIfItExists ( 'MyFormName' );

This approach offers greater adaptability and efficiency in managing form states within your application.

Answer №3

To simplify your code, consider creating a value provider object and making it accessible on the scope:

//Define value provider object
app.value("FormData", {});

app.controller("myController", function($scope, FormData) {
    //Expose on scope
    $scope.FormData = FormData;
});

Then use this object with ng-model directives like so:

Name <input ng-model="FormData.name"><br>
Rank <input ng-model="FormData.rank"><br>
SerialNum <input ng-model="FormData.ssnum"><br>

The value object is a singleton that persists throughout the application's lifecycle. Any modifications made to the object will be saved and accessible to other controllers, even if the view changes.

Check out the DEMO on PLNKR

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 method for converting this pattern into a JavaScript regex?

This code is functioning properly newRow.replace('[[' + key + ']]', item); I attempted to use regex for the replacement, but it is not working as expected newRow.replace('/\[\[' + key + '\]\]/' ...

Accessing JSON array values in a nested controller in AngularJS can be achieved by using

How can I access a Json array value in another controller? I am working with nested controllers where the nested controller should return the first character of the first name and last name. For example, if my first name is Anand Jee, it should return AJ. ...

Struggling to properly implement an "Errors" Object in the state function of a React Login Form Component

The issue arose while I was following a React tutorial. My objective is to develop a basic social media web application using Firebase, React, MaterialUI, and more. I am currently at around the 5:40:00 mark and have successfully resolved all previous pro ...

Invoke the parent's function within the Local-Registration component of VueJs

I have a Vue object: var app = new Vue({ el: '#my-id', data() { return { example: 1 } }, methods: { exampleMethos(data) { console.log('data', data); } }, ...

Is it possible to utilize a JS script generated within the body or head of an HTML file directly within CSS code?

As a beginner in webpage development, I have a query regarding the technical aspect. Is it possible to utilize variables from a JavaScript function, which is placed either in the head or body of an HTML file, directly in CSS code to make modifications such ...

JavaScript code that displays values that are not equal

Here is a code snippet that checks whether two arrays of objects are equal or not. How can we enhance this code to log which answer is not matching? The structure of the arrays: arrayA represents user answered questions, while arrayB contains correct answ ...

Error: The XML parsing in ASP failed to find a root element at the specified location

When clicking the button, I have jQuery/Ajax code that is supposed to pass the value of a selected radio button to a controller action and open a detail page. However, I am encountering an error. When using Mozilla Firefox, the console displays: XML Par ...

What is the best way to populate an array with zeros when there is no data available?

Currently, I am working on a project that involves using chart.js to display monthly profit data up to the current month. The data is retrieved from the server and there are two scenarios to consider: // First scenario data: [ ...

What is the best way to extract data from multiple functions in a single file to use in various MySQL queries?

Code snippet in Angularjs: var app = angular.module("myApp", []); app.controller("myCtrl",$scope,$http){ $scope.displayData = function(){ $http.get( "Fetch_Data.php" ).then(function (response) { $scope.names = response.data; },function (error){ ...

The error message "TypeError: 'undefined' is not a function (evaluating '_.contains')" appeared during the karma test

While executing my karma tests, I encounter a specific error during the jenkins build process. Interestingly, everything works perfectly fine when running the tests locally and all pass without any issues. However, once the same code is executed on the jen ...

Is there a way to adjust the border color of my <select> element without disrupting the existing bootstrap CSS styling?

In my Bootstrap (v4.5.3) form, the select options appear differently in Firefox as shown in the image below: https://i.sstatic.net/3suke.png Upon form submission, I have JavaScript code for validation which checks if an option other than "-- Select an Op ...

How to Ensure an Element Appears Above Another Despite Z-Index Troubles?

After conducting approximately 2 hours of research on this topic, I was unable to find clear answers or solutions. Hence, I have decided to address the issue here. The problem I'm facing is as follows: Due to the nature of HTML/CSS, it seems impossi ...

Substitute the division

Can I make the old div change its position and move to the side when I add a new div? And can all the old divs be hidden when adding four new divs? This is for my full news website and I want this applied to all four pages. First page: https://i.sstatic. ...

Safely render user-generated HTML content within a React application to prevent cross-site scripting vulnerabilities

A unique situation has arisen in our React app where a user inputs a string that is displayed to other users. The challenge lies in searching for specific characters within the string and replacing them with HTML elements. For example, transforming the wor ...

What steps are involved in adding an image to an autocomplete script?

I need help adding an image to my autocomplete script. Below is my code that I'm struggling with. My Controller: function getsearch($c_id) { $searchTerm = $_GET['term']; $query = $this->db->query("SELECT state_name FROM state ...

What steps can be taken to stop clients from sending an OPTION request prior to each GET?

Is there a way to deactivate the behavior of the client performing an OPTIONS request before every GET request? ...

Determine the validity of an image URL using Vue.js

Is there a way to check if an image URL is valid or broken in Vue.js, similar to the process outlined in Angular 2 - Check if image url is valid or broken? ...

There seems to be an issue with the function code error when calling it within the

When I attempt to run my code in this way, I encounter a compile time error stating that the expression statement is not an assignment or call... (within the else statement). What am I missing here to get it to work? I've made numerous attempts to ad ...

Having trouble locating the issue in my React application

As part of a tutorial project, I am developing an e-Commerce application using React. Currently, I am encountering an error message stating 'TypeError: Cannot read property 'length' of undefined' when dealing with a cart object. Let me ...

Encountering the error message "Angular 'Error: $injector:cdep Circular Dependency' while employing a factory in app.js"

I'm currently in the process of implementing token-based user authentication, but I've encountered a roadblock. While researching a solution, it seems like utilizing the $injector service might be the way to go, although I'm not completely c ...