Storing information from a form into an existing array using AngularJS

My script.js file contains an array like this:

 $scope.companies = [
        {
            id: '1',
            contact: 'John Doe',
            address: '123 Main Street, USA',
            function: 'Customer',
            telephone: '9876543210',
            fax: '0123456789',
            url: 'http://www.example.com'
        },

    ];

A form allows users to add a new item to the array. When the form is submitted, a new array item is created and then added ('pushed') to the existing array.

The console.log command prints out the updated array with all the data successfully.

However, when navigating to another page where the data is displayed in a table, the new item is not shown - indicating that it has not been added to the script.js file.

What steps should I take to resolve this issue?

script.js:

   // Custom module for the app
var app = angular.module("myApp", ['ngRoute', 'UserApp']);
var appName = 'My App';

// Defining routes
app.config(['$routeProvider', '$locationProvider',
    function($routeProvider, $locationProvider) {
        $routeProvider.
        // Route configuration here
        otherwise({
            templateUrl: '404.html'
        });
        $locationProvider.html5Mode(true);
    }]);

// Initialize UserApp
app.run(function(user) {
    user.init({ appId: 'REMOVED' });
});

// Dashboard Controller
app.controller("DashboardController", function($scope) {
    $scope.title = 'Dashboard';
});

// Companies Controller
app.controller("CompaniesController", ['$scope', function($scope) {
    $scope.title = 'Companies';
    $scope.title_sub = 'Add Company';

    $scope.add = function(newCompany) {
        // Add logic here to include the new company to the array
    };

    $scope.companies = [
        {
            id: '1',
            contact: 'John',
            address: 'Some street, United States',
            function: 'Client',
            telephone: '0123455858446',
            fax: '0128289385',
            url: 'http://www.example.com'
        },
    ];
}]);

// Global controller
app.controller('GlobalController', ['$scope', function($scope) {
        $scope.appName = "My App";
    }]);

// Login Controller
app.controller("LoginController", function($scope) {
    $scope.title = 'Login';
});

// Edit Account Controller
app.controller('EditAccountController', ['$scope' ,'$routeParams', function($scope, $routeParams) {
    $scope.title = 'Edit Account';
    // Update user account info
}]);

// Profile Controller
app.controller('ProfileController', ['$scope', '$routeParams',  function($scope, $routeParams) {
    $scope.title = 'Profile';
    // Fetch user profile details
}]);

add-company.html:

<div class="row">
    <div class="col-md-12>
        <h1>{{ title_sub }}</h1>
    </div>

</div>

<div class="row">
    <div class="col-md-12">
        <p>Add a new company.</p>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <form>
            <!-- Form fields for adding a new company -->
        </form>
    </div>
</div>

Edit: new controller:

app.controller("CompaniesController", ['$scope', 'companyService', function($scope, companyService) {
    $scope.title = 'Companies';
    $scope.title_sub = 'Add Company';

    $scope.add = function(newCompany) {
       // Use companyService to add the new company to the list
    };

    $scope.companies = companyService.getCompanies();
}]);   

Answer №1

When using a particular service, it is necessary to "inject" that service into each controller consistently. This can be seen in the example provided within the EditAccountController.

app.service('companyService',[function(){
     var allCompanies = [];
     return {
         addCompany: function(company){
            allCompanies.push(company);
         },
         getCompanies: function(){ 
               return allCompanies;
         }
     }
}]);

app.controller('EditAccountController', ['$scope', 'companyService', function($scope, companyService){

 $scope.companies = companyService.getCompanies();
}]);

Answer №2

Are you suggesting that once the data is submitted and saved into the array, you are navigating to a different page?

If you switch to another page, the memory stored by Javascript on the previous page will be lost. To retain the data, consider using either sessionStorage or localStorage.

One approach could be as follows:


$scope.origData = [];

$scope.addData = function(data){
 $scope.origData.push(data);
 localStorage.setItem('storedData', $scope.origData);
}

In this example, I am utilizing the native JavaScript localStorage object for database access. However, there is an angular-friendly module available for working with storage called ngStorage. You may want to explore this option.

By using the native localStorage object, you can retrieve the data from any page within your project like so:


$scope.dataOnPreviousPage = localStorage.getItem('storedData')

Answer №3

Have you considered storing the array in the $rootScope?

 $rootScope.companies = [
        {
            id: '1',
            contact: 'John',
            address: 'Some street, United States',
            function: 'Client',
            telephone: '0123455858446',
            fax: '0128289385',
            url: 'http://www.example.com'
        },

    ];

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

Finding the maximum number of elements in an array using PHP

There is a collection of cities in an array: Array ( [0] => Delhi [1] => Delhi [2] => Delhi [3] => Delhi [4] => Delhi [5] => Delhi [6] => Beng ...

Retrieve the HTML tag of an element excluding any inner text

With JavaScript, my objective is to extract only the tag, class, id, etc (the elements in brackets) of a DOM element, while disregarding the actual text content within it. This is similar to the reverse of innerHTML/textContent. Therefore, I aim to transf ...

Error Message Missing from Google Cloud Function Response

In my Google Cloud function code, I have encountered an issue where the status changes to 400 when there is an error creating a new user. However, on the client side, I always receive an "Error: invalid-argument" message regardless of the actual error from ...

Troubleshooting: Issue with Chrome's CSV Export Functionality in JavaScript/AngularJS

Currently, I am troubleshooting an issue with exporting a CSV file from a data table on a web application. The export functionality works fine on all browsers except for Chrome when the export button is clicked. I have been trying to solve this problem for ...

Creating personalized Date and Time formatting on the X axis in Lightningchart JS

I have an X-axis representing time intervals in 15-second increments. ["2020-05-22 14:20:22", "173.9"] ["2020-05-22 14:20:40", "175.3"] ["2020-05-22 14:20:58", "172.4"] In my attempt to add this data to the chart, I used the following code: for(var key ...

In ReactJS, the behavior of event.currentTarget differs from that of Vanilla Javascript

Is there an equivalent of event.currentTarget in ReactJS? When using event.target on click, I am getting the childDiv instead of the desired parentDiv. For example, in Vanilla Javascript: document.getElementById("parentDiv").onclick = function() { ...

What is the reason for the jQuery plugin not being applied after replacing the page content with an Ajax response?

At the moment, I am utilizing jQuery ajax to dynamically add content to my website. Additionally, I have incorporated the jquery.selectbox-0.6.1.js plugin to enhance the style of select boxes on the page. The plugin successfully styles the select boxes up ...

React JS: You must define 'Message' in order to avoid the react/jsx-no-undef error

As a novice learner in React JS, I am currently working on developing a messaging web application. However, as I was writing my code, I encountered the following error: Failed to compile. ./src/App.js Line 41:17: 'Message' is not defined react/j ...

Displaying received image using Express JS

Currently, I am working on managing two separate Express JS applications. One of them serves as an API, while the other application interacts with this API by sending requests and presenting the received data to users. Within the API route, I am respondin ...

The issue with Jquery.Validate not functioning properly when trying to upload a file

I have integrated jQuery validation into my ASP.NET MVC project, and it is functioning correctly with textboxes. However, I am encountering an issue with file uploads. Below is the code snippet I am using: @model ffyazilim.Management.Model.Credential.Crea ...

Exploring the connection between two MongoDB collections

I currently have two collections in my MongoDB database: Category and Book Here is the category.js code: var mongoose = require("mongoose"); var Schema = mongoose.Schema; var categoryModel = new Schema({ catName: String, menuKey: String }); module.ex ...

Utilizing Custom HTTP Headers in Angular 2 to Enhance Request Handling

Within my Angular 2 project, I am implementing the use of Http (@angular/http) to communicate with my API. In order for these requests to be successful, specific headers, including a JWT header, must be included in each API request. My goal is to have an ...

Updating a nested property within an array of objects in MongoDB

Storing grades for an online education application using MongoDB. Here is a sample classRoom document stored in my mongoDB database. StudentGradeObjs are kept in an array within a GradeObject. GradeObjs are stored in an array of GradeObjects inside a class ...

Can we include intricate items within a redux store?

As I delve into developing a React application with Redux, I encountered an unexpected scenario. At one point, we inserted a DOM element within the store, causing issues with the Redux extension that freezes when the action is triggered. Despite this compl ...

What is the process for retrieving the text element from a React component when using React.cloneElement?

Can I centralize a translation function for all table header elements? const CustomersTable = () => { var headers=<> <th>Name</th> <th>Age</th> <th>Another text</th> </> ...

The dichotomy between public and private methods within a Vue.js component

Within a component, I have two functions defined. One is foo(), which is defined within <script>, and the other is fooExported(), which is defined in the body of export default {}. My understanding is that functions inside export default {} can be a ...

React JS - Breaking down the distinction between PublicTheme and PublicTheme

In my React project, I am currently working on creating the admin dashboard and designing the UI area for user interaction. I have encountered an issue where I am unable to separate the admin theme from the PublicTheme. Even when navigating to "/admin/lo ...

The 'substr' property is not found in the type 'string | string[]'

Recently, I had a JavaScript code that was working fine. Now, I'm in the process of converting it to TypeScript. var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; if (ip.substr(0, 7) == "::ffff ...

Accessing object properties using a string for the variable name in Javascript

As I develop a Music composition program in JavaScript, I have encountered a challenge when it comes to iterating through my data quickly. My JSON object, named song, is structured like this: song = {"track0":"data...", "track1":"data...", ...}; I am con ...

Navigating a Dynamic entity using a button in AFrame

I've inquired about this topic previously, but I feel my question wasn't clear. My goal is to construct a plinko-style aframe world with a ball that resets to its starting position when clicked. While I prefer to use a button to reset the ball, c ...