Angular: Adding an object to the parent array within a modal

I am working with a modal controller in my AngularJS application, and here is an example:

angular.module('myApp').controller('ModalDemoCtrl', function ($scope, $modal, $log) {

  $scope.arrayList = [];

  $scope.newItem = function () {
    var modalInstance = $modal.open({
        templateUrl: 'newItem.html',
        controller: 'newItemCtrl',
        windowClass: 'app-modal-window',
        backdrop: 'static',
        resolve: {
        }
    });
    modalInstance.result.then(function (editable) {

        console.log($scope.arrayList);

    }, function () {
        $log.info('Modal dismissed at: ' + new Date());
    });
};

  $scope.newArrayItem = function () {
    var modalInstance = $modal.open({
        templateUrl: 'newArrayItem.html',
        controller: 'newArrayCtrl',
        windowClass: 'app-modal-window',
        backdrop: 'static',
        resolve: {
        }
    });
    modalInstance.result.then(function (editable) {

        $scope.arrayList.push(editable);

    }, function () {
        $log.info('Modal dismissed at: ' + new Date());
    });
};

My goal is to open a modal window to create a 'newItem' and then within that window, open another modal to create 'ArrayItems'. After creating each individual array item and closing the modal, I want to add that item to my $scope.arrayList. However, when I try to access $scope.arrayList after all array items are created, it appears to be empty.

It seems like I need to push the objects to the parent scope in order to access them properly. How can I achieve this?

Answer №1

I came up with a solution that may not be the most efficient, but it gets the job done.

Initially, I couldn't start the array where I wanted to; instead, I had to initialize it within the controller of the initial modal.

angular.module('myApp').controller('newItemCtrl', function ($scope, $modalInstance) {

$scope.arrayList = [];

  $scope.editable = {
    arrayList: $scope.arrayList
  };

  $scope.ok = function () {
    $modalInstance.close($scope.editable);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

Additionally, I had to incorporate it into my editable object so that it could be passed when the modal is closed.

Upon closing the second modal and creating an item for the arrayList, I simply used

$scope.arrayList.push($scope.editable);

Finally, upon closing the initial modal, I was able to log my arrayList using console.log(editable);

Although the arrayList is nested within another object (the editable object from the first modal), this setup works sufficiently for now.

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

Start up a server using Angular along with Node.js and Express framework

I am encountering an issue with configuring Express as a server in my Angular application. The app loads without any issues when accessing the HOME route, but when trying to access another route, I receive an error message: Cannot GET / This is how I hav ...

"Encountered a TypeError stating that Object(...) is not being recognized as a function" while attempting to import a function via a barrel

In one of my files, I have a function named merge which has the following code inside: export default (prev, next) => Object.assign({}, prev, next) Additionally, there is a barrel file that imports and exports this function like so: import fetchToNode ...

Matching regex only on complete strings, not on parts of strings

My goal is to dynamically add and remove strings to a textarea when values in a table are clicked. The functionality should allow users to select and deselect values in the table, with the selected values adding or removing themselves from the textarea. It ...

combining elements in JavaScript

I have two object arrays that look like this: arr1 = [ { 'v1': 'abcde', 'pv_45': 13018, 'geolocation': '17.340291,76.842807' }] arr2 =[{ 'v1':'abcde', 'pv_50&apos ...

Unraveling the Cookie with cookie-parser

I've been attempting to decode a cookie without much luck. The cookie looks like this: s%3Ak0tBm_lnBeH4G5pPIbbFKktQl0l4pNU8.d2ZbSvwFjkmVWfcS9Wn0%2Fi2oSnTYI09krfOOWJAXirE. This particular cookie was generated using the express-session module. My unsu ...

Error encountered while attempting to cast value "xxxxxx" to ObjectId in the "item" model, resulting in a CastError

I've been struggling to resolve an error while trying to delete a todo from a page using findByIdAndRemove and findByIdAndDelete methods. Despite researching and attempting various solutions, the error persists. Any assistance would be greatly appreci ...

Tips for increasing the size of a textarea

I'm attempting to extend a textarea by adjusting the margin-top property, but it doesn't seem to be working as intended. Here is the code snippet in question: #sqlcontainerLoggedInPage2 { margin-top: 60px; } <div class="container-fluid" i ...

What is the best way to combine key-value pairs objects into a single object using JavaScript?

I am faced with the challenge of creating a new object that combines keys from a specific array (const props = []) and values from existing objects. If a key does not exist in an object, I aim to populate it with null or placeholder values. Here is my cur ...

Is it possible to implement a route within a controller in Express.js?

In my controller, I currently have the following code: module.exports.validateToken = (req, res, next) => { const token = req.cookies.jwt; //console.log(token); if (!token) { return res.sendStatus(403); } try { const ...

Unable to save information in the database using Json in asp.net

I'm having trouble saving my data in a database using JSON. The code I'm currently using doesn't display any errors, but it also doesn't save the data. Can someone please help me out? I am new to working with JSON. function myfun() { ...

Webdriverio: exploring the window object

I am experimenting with Webdriverio Testrunner using Selenium Standalone. I have encountered an issue while trying to check a global variable (window.myVar) in one of my tests. When attempting to return the window object, I am getting unexpected results i ...

Error Encountered when Using JQuery AJAX: Unexpected Identifier Syntax Issue

I've been struggling with a strange error for quite some time now. I want to believe that this is one of those errors where the solution will magically appear, but only time will tell. Here's the piece of code causing the issue: var images = ...

The icon is being displayed as text instead of the actual Fontawesome icon

Using jquery version 3.3.1 I am dynamically creating an anchor tag: let link = $("<a>"); link.attr("href", "#"); link.text("My anchor" + ' <i class="fas fa-people-carry"></i>'); However, when I try to display ...

What is the best way to populate an AngularJS list using a for loop or an array?

After reviewing this code that has been hard coded, I have identified the following: $scope.years = [ {id:curryear, name: curryear} {id:curryear - 1, name: curryear - 1} {id:curryear - 2, name: curryear -2} ]; My current task involves populating ...

Simulated alternate identities for UI Router

I am managing a group of pages/URLs that share a common parent state/template: /orders/list /orders/create /products/list /products/create Currently, I have two dummy states/routes (/products and /orders) that serve as parent states for the other substat ...

Personalized HTML selection list

When a select option is too long, it stretches the container to accommodate its length. I have created a truncate function to limit the display to 20 characters and add ellipses to prevent this stretching. I have been searching for a way to show the entir ...

Is there a way to automatically retrieve CSV data using ashx on a web page?

After researching the provided links from SO without success, I decided to reach out here for help. (For privacy reasons, the actual URL and header data have been obscured) I am struggling to automate downloading data from an HTTPS web page using Delphi ...

I need help creating a Google marker using the Maps JavaScript API

I am currently working with the Google Maps API. The map displays the latitude and longitude when a mouse click event occurs. My next step is to add a Google marker to the map. Below is my JavaScript code snippet: <script> function initMap() ...

When the regex.test function is not functioning correctly in a Vue.js JavaScript router, issues may arise

const router = createRouter({ history: createWebHistory(), routes, }); // ... const allowedToAnonymous = [ /^\/login$/g, /^\/signup$/g, /^\/home$/g, /^\/emailconfirm\/[0-9a-zA-Z]{8}$/g, /^\/serviceGuide$/g, / ...

The paths required are not correct following the transpilation of a TypeScript file using Babel

Issue Every time I use nodemon with npm run start, I encounter the error message "Error: Cannot find module 'Test'". Similarly, when I build files using npm run build and try to run ./dist/index.js, I face the same issue. It seems that the requ ...