The AngularJS modal is sending back the results before updating the parent scope

When launching a modal from my web page, I am updating an array passed from the parent. However, when closing the modal and sending back the updated results, the parent scope object is also being updated. If the user decides not to update and cancels the modal, I do not want those changes reflected in my parent controller.

  • Parent Controller Code:

    const modalInstance = $modal.open({ templateUrl: '/app/modal.html', controller: 'modalController', controllerAs: 'modal', resolve: {
    mappedData: () => parentCntrl.groupData } });

            modalInstance.result.then(result => {
                if (result) {                   
                    parentCntrl.groupData = result;
                }
            });
    
  • Child Controller Code:

    modal.ok = () => { $modalInstance.close(modal.mappedData); };

    modal.close = () => { $modalInstance.close(); };

Answer №1

When passing non-primitive data types, like objects or arrays, in JavaScript, the reference to the original data is passed instead of a copy.

To prevent unintended changes to the original data, it is recommended to create a copy of the data before making any modifications. This copied version should be used within the modal, and any changes made should be merged back to the original object in the parent controller upon saving.

A similar question addressing reference issues when using AngularJS can be found here. It explains how the angular.copy() function can be utilized to avoid these reference problems.

Answer №2

When creating a new $uibModal instance, it is important to specify a configuration object. In this object, the scope : should point to the scope that the modal will use. Typically, you would set it as scope: $rootScope. This ensures that any variables with matching names in the modal controller and parent scope are referring to the same object. Some suggestions from comments include using angular.copy() or $rootScope.new();

var modalInstance = $uibModal.open({
  ...
  scope : $rootScope.new(),
  //or
  scope : angular.copy($scope)
  ...
});

I trust that this information proves useful.

Answer №3

Give this straightforward code a try.

HTML:

<tr ng-repeat="users in list">
  <td>{{users.firstname}}</td>
  <td>{{users.lastname}}</td>
  <button class="btn btn-primary" data-toggle="modal" data-target="#myModal" ng- 
  click="selectUser(users)">Edit Info</button>
</tr>

Controller:

$scope.selectUser = function(users){
            $scope.clickedUser = users;
            $scope.modalInfo = angular.copy($scope.clickedUser);
    };

Modal:

<div class="modal fade" id="myModal" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h2 class="modal-title">Update bio</h2>
        </div>
        <div class="modal-body">
            <input type="text" ng-model="modalInfo.firstname">
            <input type="text" ng-model="modalInfo.lastname">
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div>
</div>

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

Issue with Caching during Javascript Minification

I Have ASP.Net MVC 3 App. Utilizing YUICompressor.Net for compressing Javascript and CSS files post build with MSBuild. The minimized javascript file is named JSMin.js and the CSS file is CssMin.css. In my master page, I reference these files as shown bel ...

handle an exception within the initializer of its object

I'm currently working with an Ajax object that is utilized in various other objects to load 'Json' files. One issue I'm facing is trying to catch the 404 'Not found' exception thrown in the initializer object. However, every ...

Having trouble installing handlebars on Node using the command line

I've been attempting to integrate handlebars with node using the instructions from my book. The guide advised me to install handlebars like so: npm install --save express3-handlebar. However, this resulted in an error npm WARN deprecated express3-han ...

What is the best way to obtain a reference to the parent form element within an AngularJS directive?

Here is the HTML code I am working with: <form name="my-form"> <div class="col-sm-4"> <input type="phone" name="mobileNumber" ng-model="form.mobileNumber" value="0439888999" required> </div> </form> In addition, I ha ...

Is the accuracy of the in-situ convolution filter guaranteed?

After analyzing my simple box blur function, I have come to the realization that it may be incorrect. The current implementation edits the ImageData object in place, leading to convolution filters depending on surrounding pixels that have already been ch ...

I am attempting to load the ajax content into separate divs simultaneously

When I attempt to load the ajax into two separate divs, I notice that despite calling for data to be placed in two different divs within the ajax code, it all ends up in one div. <script>$(document).ready(function(){ $.ajax({ url: "http: ...

Tips for effectively redirecting traffic to another website

Is there a way to redirect someone from a page URL like example.com/2458/233 to example2.com/2458/233? The first URL contains only a file that redirects to the other domain. Can anybody provide instructions on how to achieve this process? To clarify furt ...

Discover the method to retrieve every element from a Listbox with the click of a Button and utilizing an ajax call

How can I retrieve all the elements from a Listbox when a Button Click event triggers an ajax call? I have created a function that successfully returns all the elements from the Listbox. However, when I try to bind it with the ajax call, it doesn't w ...

Switching the background color of alternating divs in reverse order: a step-by-step guide

I am looking to alternate the background color of divs between odd and even, with the last div being grey and the second to last div being green. I have tried using the odd/even classes in CSS, but it did not work as expected. .main{ width:500px; height ...

Changing text on a button with JavaScript toggle functionality: A step-by-step guide

I am looking to implement a feature where I can hide and show overflow content in a div. When I click on the expand button, it expands the content. However, I want this button to toggle and change text as well. Thank you! function descriptionHeightMo ...

Fill the dropdown menu with JSON keys

My challenge involves working with an array containing objects, which are sent to the client via a node.js server integrated with mongodb. I need to extract all keys/fields from the object (such as name, surname, telephone) without their values (for exampl ...

Ways to limit Javascript math results to two decimal points and erase previous output in one go

Working on a JavaScript multiplication task. The input provided is multiplied by 0.05. The JavaScript code successfully multiplies the input number by 0.05, but encounters some issues: The calculated value should be rounded to two decimal points. For ex ...

What is the best way to display an object in Vue.js once it has been retrieved through an AJAX request?

Imagine having the following HTML code: <div id="app"> <h2>List of Items</h2> <table border="1"> <thead> <tr> <th>Name</th> ...

How can I dynamically adjust an element's attribute as a user scrolls past it (creating a sticky effect)?

For instance, when you visit and try scrolling up, you will notice a bar displaying: "Typography Code Tables Forms Buttons Icons by Glyphicons" As you continue to scroll past the element, a class is added to alter the appearance. However, as you scrol ...

Executing Promises in an Array through JavaScript

LIVE DEMO Here is a function provided: function isGood(number) { var defer = $q.defer(); $timeout(function() { if (<some condition on number>) { defer.resolve(); } else { defer.reject(); } }, 100); return defer.pro ...

Changing the entire content of a webpage from the server using AJAX

I am looking to update the entire page content with the click of a button, transitioning from Words.html to SelectNumber.html This snippet is from Words.html <html> <head> <meta charset="UTF-8"> <title>Number Game< ...

What is the best way to reset an event back to its original state once it has been clicked on again

As a newcomer to web development, I'm currently working on creating my own portfolio website. One of the features I am trying to implement is triangle bullet points that can change direction when clicked - kind of like an arrow. My idea is for them to ...

Where should uploaded files be stored using ng-flow?

Initially, I am utilizing the ng-flow, which is an html5 file upload extension built on the angular.js framework. After uploading my files and logging the event in the console, I'm uncertain about where and how to store them. Below is my HTML code w ...

Pressing the non-responsive button automatically chooses the following item

This example demonstrates how to create a disabled button: import { Grid, IconButton } from "@material-ui/core"; import ArrowBackIosIcon from "@material-ui/icons/ArrowBackIos"; export default function App() { const handleClick = (e) ...

Regular expression: Validate in PHP (on the server-side) or JavaScript (on the client-side)

I am working on a form that validates user input using PHP, JavaScript, and AJAX. I plan to use regex to validate each field, but I'm unsure about which method is best for checking it... In your experience, do you recommend using JavaScript or PHP fo ...