I have two ng-controller instances that require sharing data between them

Greetings! Currently, I am working with 2 controllers in my app.js file.

app = angular.module('dbaccess',[]);
app.controller('process', function($http, $scope,$location, $service){
    $scope.update = function(user){
        $scope.master = {};
        $scope.master = angular.copy(user);
        $http.post("http://localhost:8080/dbaccess/saveData", $scope.master).success(function(data, status, headers, config){
            $scope.resp = data;
            alert("This is the data" +data.message);
            $('.form-horizontal').hide();
            $('#response-message').html().text("Hello");                    
        })
        .error(function(data){
            alert("Error " +data.message);              
        })
    }
});
    app.controller('usrEmailAddress', function($http,$scope,$location, $service){
        $scope.email = {};          
        $http.get("http://localhost:8080/dbaccess/userlist").success(function(data){
            $scope.emails = data;
        }); 
    })

The 'process' controller is used to submit data to a Java controller for processing, while 'usrEmailAddress' controller fetches JSON data from the Java controller.

I am currently facing an issue with passing email information from my index.jsp page to the process controller. Any guidance on this matter would be highly appreciated.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html> 
<html lang="en" ng-app="dbaccess">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Page Title Example</title>
        <link rel="stylesheet" href="/dbaccess/resources/css/bootstrap.min.css">               

        <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
    </head>
     <body>
        <div class="container" ng-controller="emailAddress as address" >
            <div class="row">
                <div class="col-lg-12"></div>
            </div>
            <form class="form-horizontal" data-toggle="validator" role="form">
                 <div class="form-group">
                    <label for="requestedBy" class="col-sm-2 control-label"> Requested By</label>
                     <div class="col-sm-3">
                        <input type="text" class="form-control" id="requestedBy" placeholder="Requestor Name" ng-model="user.requestedBy" required/>
                     </div>
                </div>
                 <div class="form-group">
                     <div >
                        <label for="email" class="col-sm-2 control-label"> Email Address</label>
                         <div class="col-sm-3 " ng-controller='usrEmailAddress'>
                            <select class="form-control" ng-model="user.email">
                                <option value=""> --Select Email Address -- </option>
                                <option ng-repeat="mails in emails" value={{mails.email}} >{{mails.email}}</option>
                            </select>
                        </div>  
                    </div>
                </div>
              ...
            </form>
                <pre>form = {{user | json}}</pre>
                 <pre>master = {{master | json}}</pre>
        </div>  
    </body>

        <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>

        <script src="/dbaccess/resources/js/angular.js"></script>
         <script src="/dbaccess/resources/js/bootstrap.min.js"></script>
          <script src="/dbaccess/resources/js/bootstrap.js"></script>
        <script src="/dbaccess/resources/js/example.js"></script>
        <script src="/dbaccess/resources/js/validator.min.js"></script>
    </body>
</html>

Answer №1

To manage data in your Angular project, you can utilize either a service or a factory.

Take this example:

app.factory('contactService', function($q, $http) {
  var contacts;

  var getContacts = function() {
    var deferred = $q.defer();
    if (contacts) { 
      deferred.resolve(contacts);
    } else {
      $http.get("http://localhost:8080/database/contacts")
        .then(function(data){
          contacts = data;
          deferred.resolve(contacts);
        }); 
    }

    return deferred.promise;
  };

  return {
    getContacts: getContacts
  }
});

In the code snippet above, $q is used to ensure that a promise is always returned. Whether the $http call is made or not, you will receive a promise. The method will either return the list of contacts already stored in memory, or fetch the contacts, save them in memory, and then use them.

The controllers in your application only need to inject the contactService and invoke getContacts.

app.controller('userContacts', function($scope, contactService){
  contactService.getContacts().then(function(contacts) {
    $scope.contacts = contacts;
  });
});

app.controller('processData', function($http, $scope,$location, $service, contactService){
  // [...]

  contactService.getContacts().then(function(contacts) {
    $scope.contacts = contacts;
  });
});

The first service that calls getContacts will populate the data.

Answer №2

When it comes to AngularJS Services, they play a crucial role.

Angular services are objects that can be interchanged and connected through dependency injection (DI). They help in organizing and sharing code within the app.

To delve deeper into services, check out the AngularJS documentation.

It's important to note that AngularJS Services act as singletons, existing as a sole instance and only being initialized when needed by an application component.

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

When clicked, elevate the element to the top of the window with an offset

Is there a way to click on this button, which is located within an accordion section header, and have it automatically move to the top of the page based on the window size? It seems like it should be a simple task, but sometimes after a long day things ca ...

locate an inner div element

Here are two div elements: <body> <div id="divParent"> <div id="divChild"></div> </div> </body> What is the best way to select the divChild element using JavaScript? ...

manage dynamic form data in React using Ant Design components

My attempts to work with dynamic forms using React and Ant Design have been challenging. Despite my efforts to find solutions online, I have had no luck. Here is a CodePen link where I have recreated the issue I am facing: https://codepen.io/sethen/pen/Rwr ...

Redux: triggering a dispatch when a component or function is initialized

I'm facing a challenge where I need to update a state only when a specific functional component is initialized. My initial approach was to try something like this: export default function SalesFeedPage(){ const {salesFeed} = useSelector((state) => ...

I'm curious if anyone has experimented with implementing TypeScript enums within AngularJS HTML pages

During my Typescript project, I defined an enum like this: enum Action { None = 0, Registering = 1, Authenticating = 2 }; In the controller, I declared a property named action as follows: class AuthService implements IAuthService { action: number; ...

Failed to load TypeScript file or similar issue

Whenever I attempt to generate a TypeScript file from a partial view (MVC .NET) that is loaded through a rest call and then appended to a div element, I encounter an error in my console. The error message reads: Uncaught ReferenceError: xyz is not defined ...

Moment.js generated an error due to an unhandled promise rejection warning

I'm trying to determine if my current timestamp is equal or greater than a certain value, but I keep encountering errors. Here's my code with the error: {...} exports.validaforgotpass = async (req, res) => { {...} const results = aw ...

Encountering an undefined value from state when implementing useEffect and useState

One issue I am facing is that the state of my projects sometimes returns as undefined. It's puzzling to me why this happens. In the useEffect hook, I have a function that fetches project data from an API call to the backend server. This should return ...

What is the best way to ensure that my image completely occupies the div?

I am facing a challenge in creating a hero image that would completely fill the div on my webpage. Despite setting the width and height to 100%, the image seems to only occupy half of the space. Check out the CSS and HTML code snippet here. div.hero{ ...

What is the best way to send user input text to a Vue method using v-on:change?

I am trying to pass the input value from my HTML to a Vue method called checkExist(). I need to get this value within the checkExist() method. Can anyone provide advice on how I can achieve this? I am new to Vue and could use some guidance. HTML: <inp ...

Using ReactJS to Deconstruct Data within Class Components

I have a file named Context.js with the following content: const AppContext = createContext({ // ... color palette scheme color1: '#ADBDDB', color2: '#7F8EB2', color3: '#546287', color4 ...

"After refreshing the page, the .load() function did not run as

After loading the page and adjusting the viewport size, I am trying to retrieve the dimensions of images. While I can successfully get image dimensions after the page loads using .load, I am struggling to find a way to update the image sizes when the viewp ...

How can ternary conditional operators be transformed into if statements?

When dealing with minified code like this, f&&!f.error?k.button.b==k.button.c.G?k.button.Q(b,e,f,c,d):k.button.b==k.button.c.o&&k.button.P(b,e,f,c,d):(console.error(f),f=f.error.message||chrome.i18n.getMessage("error_tooltip"),k.button.v(b ...

Issue with React-Axios: File data being sent to Node server is undefined

My current challenge involves uploading a single file and saving it in a specific folder within my app directory. While I can successfully choose a file on the frontend and update the state of the Uploader component, I encounter an issue when sending a POS ...

Can you explain the key distinction between the backtick (`) and the ampersand-hash-39

I am completely new to TypeScript, JavaScript, and Angular. As I follow some tutorials, I often encounter code snippets like the one below: class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return `(${this.x}, ${th ...

How to dynamically update data in Angular without the need for a page refresh or loading?

Looking to enhance a wishlist feature by enabling users to delete items from the list without the need for a page refresh. Here's my approach: wish.controller('wishCtrl',['$scope','$http','$cookies','$wind ...

How can I swap a string for a symbol in JavaScript?

Is there a way to convert the text @abc some text here to <a href="some_url">@abc</a> some text here using JavaScript? Are there any libraries that can help with this task? ...

How can I open a new window, redirect the current one, and bring focus to the new window using JavaScript?

Trying to troubleshoot a problem I'm having with the following setup: - Using SAP Portal, I am launching an HTML page containing this code. - The goal is for the HTML page to open a new window. - Once the new window opens, the original HTML page ...

Differentiating between mouseenter and tap events: What's the key?

When a mouseenter event is present, touch-enabled devices will activate this event when the user taps on the element. Is there a way to differentiate between an actual physical mouse entering and a simulated tap (which resembles a mouse enter)? ...

npm ERROR! 404 Content removed by unidentified source on August 8, 2022 at 09:20:35.527 UTC

Upon running the command <npm view e-biz-znnf versions --json> in the terminal, npm throws an error message: npm ERR! code E404 npm ERR! 404 Unpublished by undefined on 2022-08-08T09:20:35.527Z npm ERR! 404 npm ERR! 404 'e-biz-znnf' is no ...