I require a platform that can effectively store, retain, and provide access to information across various interfaces

Although it may seem like a basic issue, as someone new to Angular, I'm facing a problem. I have 2 views that both require access to the same user input data from a form. Each view has its own controller.

Here's the current situation:

JAVASCRIPT

.config(function($routeProvider) {
    $routeProvider
    .when('/view1', {
        templateUrl : 'view1.html',
        controller: 'ctrl1'
    })
    .when('/view2', {
        templateUrl : 'view2.html',
        controller : 'ctrl2'
    })
})

//SERVICE TO STORE DATA
.service('Data', function() {
    return {};
})

//CONTROLLER 1
.controller('ctrl1', ['$scope', 'Data', function($scope, Data) {
    $scope.data = Data;

    var $scope.initValue = function() {
        $scope.data.inputA = 0; //number
        $scope.data.inputB = 0; //number
    }

    var $scope.onSubmit = function() {
        $scope.data.result = $scope.data.inputA + $scope.data.inputB;
    }
}])

//CONTROLLER 2
.controller('ctrl2', ['$scope', 'Data', function($scope, Data) {
        $scope.data = Data;
    }
}])

HTML (view2.html)

<p>The result is {{data.result}}</p>

Currently, nothing is being displayed. Could it be due to the service or controller resetting the values when switching views? Is using a service for this purpose completely wrong?

Answer №1

Make sure to update the data within the service for cross-controller usage:

// Create a variable container within the service
// Enhance readability by implementing a getter and setter
.service('Data', function() {
    var value = null;
    var setValue = function(val) {
        this.value = val;
    };
    var getValue = function() {
        return this.value;
    };

    return {
        value: value,
        setValue: setValue,
        getValue: getValue,
    };
}

In controller 1, you can update the value in the service like this:

//CONTROLLER 1
.controller('ctrl1', ['$scope', 'Data', function($scope, Data) {
    $scope.inputA = 0;
    $scope.inputB = 0;

    $scope.onSubmit = function() {
        $scope.result = $scope.inputA + $scope.inputB;
        Data.setValue($scope.result);
    }
}])

And in controller 2, you can access the value like this:

//CONTROLLER 2
.controller('ctrl2', ['$scope', 'Data', function($scope, Data) {
    $scope.value = Data.getValue();
}])

This method should provide a solution for your needs.

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

Implementing a Node.js catch-all route that redirects all incoming requests to the index page, which will then be rendered

After attempting to implement a catch-all route and using res.redirect('/'), I noticed that regardless of the URL entered, it always redirected to the index or home page. It seemed like Angular wasn't recognizing the full URL. However, when ...

Switching between two identical components can be easily achieved with VueJS

Assume I have a file named foo.vue, which I import into the parent component as components called a and b, and they are displayed based on a variable called show. When switching between components a and b in the parent without setting show = null, various ...

Utilizing the map function in React to create a button reference

I am currently facing an issue that is relatively simplistic and doesn't have any real-world application. My goal is to locate a 'green' button and make it blink for a duration of 3 seconds. How can I achieve this using React? const btnLay ...

Display Page Separation with JavaScript

I am working on a project where I have created payslips using Bootstrap through PHP. To maintain organization, I am looking to create a new page after every 6 payslips. Below is the code snippet that I am using to generate the payslips: foreach($results a ...

Unresolved issue with AngularJS radio button binding

As a beginner in using Angular.js, I encountered an issue with data binding when dealing with radio buttons. The HTML code in question is: <label class="options_box" ng-repeat="item in item_config_list.item_config"> <input type="radio" name ...

Display validation errors in Angular2 forms when the form items are left empty and the user tries to submit the form

In my application, I have a userForm group containing keys such as name, email, and phone. Additionally, there is an onValueChanged function that subscribes to changes in the form and validates the data. buildForm(): void { this.userForm = this.fb.gr ...

What is the best method for passing parameters from HTML to AJAX within code?

My project involves working with Flask, HTML, and Ajax. Here is the HTML code snippet: <script type=text/javascript> $(function() { $('a#calculate').bind('click', function() { $.getJSON('/_add_numbers&ap ...

In Internet Explorer, the AngularJS multiple select box becomes unselectable when there is a change in the scope

Having an issue with multiple select boxes using AngularJS. Everything works fine in Chrome, but in IE, after changing the scope, I am unable to select anything - it freezes the UI. I have two multiple select boxes where you can select a set from one and ...

Enable content to be displayed when hovering over it with a mouse in

As a newcomer to JavaScript, I am eager to learn how to add an interactive feature to my menu item. I want to create an info box that pops up when the menu item is clicked, and can also be displayed when hovering over it. Below is the script I have so far, ...

Is it possible to dynamically change the color of text based on its position using CSS, JS, or JQuery?

I am currently working on a corporate website and have been tasked with creating a unique design for a specific page. The design includes the following elements: A body background gradient that transitions from their primary color to white in a top-to-bot ...

Tips for automatically resizing a canvas to fit the content within a scrollable container?

I have integrated PDF JS into my Vue3 project to overlay a <canvas id="draw_canvas"> on the rendered pdf document. This allows me to draw rectangles programmatically over the pdf, serving as markers for specific areas. The rendering proces ...

Best practices for securely storing JWT tokens from an API in next-auth

I followed an online tutorial to implement this in next-auth import NextAuth from "next-auth" import Providers from "next-auth/providers"; const https = require('https'); export default NextAuth({ providers: [ Providers ...

Utilize Haxe Macros to swap out the term "function" with "async function."

When I convert haxe to JavaScript, I need to make its methods asynchronous. Here is the original Haxe code: @:expose class Main implements IAsync { static function main() { trace("test"); } static function testAwait() { ...

Executing numerous GET requests with varying parameters in AngularJS

Update: My apologies to those who answered, it turns out that the code was correct, but requests were being intercepted and losing all parameters. I am attempting to send repeated HTTP GET requests to a REST API based on the response, using the solution I ...

Combining NodeJS with Javascript for wrangler bundling: A guide

The challenge: My goal is to create a Cloudflare worker that utilizes NodeJS dependencies. Unfortunately, I'm facing obstacles with Wrangler, preventing me from deploying it using the command wrangler deploy. The obstacle: X [ERROR] Could not resolve ...

Troubleshooting in Electron: What is the best way to access objects within the render scope from the console?

During my experience in web development, I have always appreciated the ability to access and manipulate variables and functions through the browser's development console at runtime. For instance, if I define a var foo = 3; in my code, I am able to ...

Issues with Google API Column chart example in jsfiddle demonstration are hindering its functionality

I'm attempting to make the Google Column Chart example provided here function properly. Here is my effort: http://jsfiddle.net/dwNE4/ (Note: I'm having some difficulty getting it to load) This is the code from the fiddle: HTML <script src=&q ...

Issue 1054 - The variable being used as a field in the WHERE clause is being interpreted as a column

While attempting to update a mysql database, I encountered an error where the variable 'id', which is used as a field in the WHERE clause, is being interpreted as a column name. Am I misreading this? What needs to be corrected in order for this q ...

Issue with redirecting to a single page on a public URL when utilizing thinktecture

In my development project, I am working on a single page application using AngularJS, Aspnet, and Thinktecture. One of the features includes a login screen hosted on Thinktecture (localhost:44304) for customer authentication. Upon successful login, the use ...

Creating a callback function within its own definition

I need help with my download function that is calling a callback to "downloadCallback". Is it possible to define the downloadCallback function inside the download function itself? If so, how can I achieve this? Below is the implementation of the download ...