What is the best way to transfer data between views in AngularJS?
I tried using $rootScope but it's not working as expected.
What is the best way to transfer data between views in AngularJS?
I tried using $rootScope but it's not working as expected.
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;
}
});
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.
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
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 + '\]\]/' ...
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. ...
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 ...
I have a Vue object: var app = new Vue({ el: '#my-id', data() { return { example: 1 } }, methods: { exampleMethos(data) { console.log('data', data); } }, ...
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 ...
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 ...
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 ...
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: [ ...
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){ ...
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 ...
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 ...
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 ...
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. ...
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 ...
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 ...
Is there a way to deactivate the behavior of the client performing an OPTIONS request before every GET request? ...
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? ...
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 ...
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 ...
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 ...