Store information in Factory and retrieve it in the controller

I am encountering an issue with my code.

Below is the factory code:

.factory('shareDataService', function() {
    var sharedData = {};

    sharedData.shareData = function(dateFrom, dateTo) {
        var from = dateFrom;
        var to = dateTo;
        alert(from + to);
    };
    return sharedData;
})

And this is the controller:

.controller('getFormDataCtrl', ['$rootScope','$scope', '$http', 'shareDataService', function ($rootScope,$scope, $http, shareDataService) {
  $scope.getFromBase = function () {
    shareDataService.shareData($scope.dateFrom, $scope.dateTo)       
  }

  $scope.bookingFormSubmit = function (){
    var array = {
        "from": ''// i want put dateFrom HERE,
        "to": '',// i want put dateTo HERE
        "yacht": $rootScope.yacht_id,
        "customer": {
            "fistname": $scope.firstname,
            "lastname": $scope.lastname,
            "birthday": $scope.birthday,
            "phone": $scope.phone,
            "email": $scope.email,
            "country": $scope.country,
            "city": $scope.city
        }
    }
  }}])

This page is developed using Symfony2 and Symfony2 forms. The initial form allows customers to select a start date and end date, with a button labeled "getFromBase()".

I aim to store this data in order to utilize it at a later time.

The subsequent form is displayed in another UI view. Here, customers input their personal details (such as name, last name, etc.). Upon clicking "bookingFormSubmit()", I retrieve all the data from this form. I also need to incorporate the data from the factory (the two variables) to create a JSON object.

Answer №1

This specific information contained in the service is considered sensitive. In order to access it, you must broaden the scope and make use of an accessor.

Data Service

.factory('shareDataService', function() {
    var sharedData = {};
    var from, to;

    sharedData.getSharedData = function ()
    {
      return {from: from, to: to};
    };

    sharedData.shareData = function(dateFrom, dateTo) {
        from = dateFrom;
        to = dateTo;
    };

    return sharedData;
})

Instructions for Use

.controller('getFormDataCtrl', ['$rootScope','$scope', '$http', 'shareDataService', function ($rootScope,$scope, $http, shareDataService) {
  $scope.getFromBase = function () {
    shareDataService.shareData($scope.dateFrom, $scope.dateTo)       
  }

  //NEW
  var data = shareDataService.getSharedData;

  $scope.bookingFormSubmit = function (){
    var array = {
        "from": data.from, //NEW
        "to": data.to,     //NEW
        "yacht": $rootScope.yacht_id,
        "customer": {
            "fistname": $scope.firstname,
            "lastname": $scope.lastname,
            "birthday": $scope.birthday,
            "phone": $scope.phone,
            "email": $scope.email,
            "country": $scope.country,
            "city": $scope.city
        }
    }
  }}])

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 process for integrating three.js code manually into an iframe?

I recently posted a question on Stack Overflow inquiring about how to input code into an iframe without using a file or URL. While I was successful with simple cases like <h1>Hello World</h1>, my ultimate goal is to integrate three.js into thes ...

Alert Box Displays Variable Name Instead of Label Name in Form Validation - MM_validateForm()

Looking at the screenshot, you can see variable names such as "email_address", "email_message" and "email_subject". I would like these to be displayed as "Email", "Message" and "Subject" instead. The validation in this form is done using MM_validateForm() ...

Issue encountered while retrieving information from XML file through AJAX

I am facing an issue while using AJAX to fetch data from an external XML file. The error I receive is "Invalid argument" and I am working with IE 8. Below is the code snippet: var xhr; xhr = new XMLHttpRequest(); xhr.open("GET","C:/Users/abc/Desktop/Pr ...

Once an item is added, the table vanishes into thin air

I have a DataTables setup to show a list of project names, and I have a button that should add an item to the displayed array. However, when I click the button, the table disappears. Below is the code snippet: view.html <button ng-click="vm.add()"> ...

The absence of a semi-colon in JSLint

I encountered an error message indicating a semicolon is missing, however I am unsure of where to place it. Here is the snippet of code: $('.animation1').delay(350).queue(function(){ $(this).addClass("animate-from-top") }); ...

Tips for invoking a url with JavaScript and retrieving the response back to JavaScript

I am trying to make a URL call from JavaScript with a single parameter, and the URL should respond to that specific request. Here is an example of the response format: {"success":true, "result": {"token":"4fc5ef2bd77a3","serverTime":1338371883,"expireT ...

Creating an array of logos in ReactJS with the help of TailwindCSS

After seeing multiple implementations of this feature, I find myself struggling to search for a solution. I can only access the HTML and CSS through inspecting elements, wondering if others are facing the same issue as me. Typically, we aim to implement t ...

How come the item I just inserted into a JavaScript array is showing up as undefined when I try to retrieve it immediately after adding it?

Apologies for the messy code, but I'm facing an issue with my JavaScript. I can't figure out why the specified child is not considered as a task to derive from: var childrenToOperateOn = []; for (var i = 0; i < $scope.der ...

The Ajax response is coming back with a null value, but upon inspecting the network response

I'm facing a strange issue where one specific value from an ajax json response is showing up as an empty string, while all other values are appearing correctly. An unusual aspect of this problem is that the network panel displays the correct value in ...

Retrieving a variable value set within a jQuery function from within an Angular 2 component

In the current project, I am facing a situation where I need to work around and initialize jQuery datetimepicker inside an Angular 2 application (with plans to refactor it later). However, when I assign a datetime value to a variable, I encounter a proble ...

Navigating to the bottom of a specific element by scrolling

I am currently working on enhancing a module within the application I'm developing. The goal is to automatically scroll the browser window to the bottom of an element when said element's height exceeds the height of the window. The functionality ...

What is the best way to create hover effects on buttons in Vue.js 3?

I'm currently developing a calculator to practice my Vue.js 3 skills (I am new to vue). I've successfully implemented the basic features, but now I'm exploring how to incorporate hover animations on the buttons. Specifically, I want to diffe ...

Struggling with Implementing jQuery for Triggering Multiple Functions on a Single Change Event?

I am currently developing jQuery functions that create dependencies between the css classes of different inputs in a web form. For example, when a specific input has a certain value, the "hide" class is removed from another input. One working example of t ...

Verifying dynamic number inputs generated using JavaScript values and calculating the total with a MutationObserver

Preamble: I've referenced Diego's answer on dynamic field JS creation and Anthony Awuley's answer on MutationObserver for the created fields. After extensive searching, I found a solution that meets my needs, but it feels somewhat bulky des ...

Show the Vue.js template in a Laravel Blade view

I have been struggling to integrate a Vue.js component into a Laravel blade file. Despite researching tutorials and Stack Overflow solutions, I have not been able to resolve the issue. Below is the template that I want to display: <template> < ...

What is the best way to immediately update the state in a React functional component?

Having recently started learning React, I find myself struggling to understand the lifecycle of a functional component. Let's consider a scenario where I have multiple checkboxes labeled as: checkbox, a, b, c, and d, each corresponding to values a, b, ...

JavaScript: Repeated Depth First Exploration for hierarchical rearrangement implemented with d3's recursion()

I'm attempting to perform a depth-first search on a complex JSON object, such as the one available through this link. My goal is to generate a modified object structure that looks like this: [ { name: "Original Object", children : [ ...

Increase the detection range in empty lists for Vue-draggable-next

I am currently utilizing Vue-draggable-next in conjunction with Vue 3 to enable draggable lists within my application. In certain scenarios, users need to drag items from other lists into lists that are initially empty. I have noticed that the area for det ...

Retrieving the input[text] value in TypeScript before trimming any special characters

One of the tasks I am working on involves a form where users can input text that may contain special characters such as \n, \t, and so on. My objective is to replace these special characters and then update the value of the input field accordingl ...

Obtain an array from an Ajax request using jQuery Datatables

I have integrated the jQuery DataTables Select plugin into my project to enable the selection of multiple rows from a table and storing their data inside an array. Subsequently, I am attempting to make an Ajax Request to pass this array to another PHP file ...