The issue arises when attempting to use the cancel button to exit the editing modal for an item within an ng-repeat loop, while

In my project, I have set up a ng-repeat loop to display blocks that can be edited in a modal window. The goal is to allow users to make changes and then cancel the window to discard any modifications. While the modal window is functioning correctly and editing blocks as intended, I am encountering an issue with reverting changes back to the original element when the cancel button is clicked.

Below is the HTML code for the ng-repeat section:

  <div class="container" style="max-width: 600px;">
<div ng-repeat="block in blocks" class="text-muted" ng-drop="true" ng-drop-success="onDropComplete($index, $data ,$event)">

    <!-- Block Content -->
  
</div>
</div>

Here is the markup for the modal:

  <script type="text/ng-template" id="myModalContent.html">
    <div class="modal-header">
      <h3 class="modal-title">Edit Block</h3>
    </div>
    <div class="modal-body">

        <!-- Form Fields -->
        
      <form class="form-group">
        <input class="form-control" placeholder="Title" type="text" ng-model="block.title"/>
        <input class="form-control" placeholder="Main Body" type="text" ng-model="block.body"/>
        <button class="btn btn-success" type="submit" ng-click="saveBlock()">   Save  </button>
        <button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
      </form>
      
    </div>
  </script>

Lastly, here is the relevant controller logic:

$scope.modalUpdate = function (selectedBlock) {

var modalInstance = $uibModal.open({
  animation: $scope.animationsEnabled,
  templateUrl: 'myModalContent.html',

  controller: function($scope, $uibModalInstance, block){
    $scope.backUp = angular.copy(block);
    $scope.block = block;

    $scope.saveBlock = function () {
      $uibModalInstance.close($scope.block);
    };

    $scope.cancel = function () {
      $scope.block = angular.copy($scope.backUp);
      $uibModalInstance.dismiss('cancel');
    };
  },
  size: 'sm',
  resolve: {
    block: function () {
      return selectedBlock;
    }
  }
});

Despite implementing the cancel functionality, changes to the block remain persisted after clicking cancel. Any advice on resolving this issue would be greatly appreciated!

Answer №1

Attempt to eliminate the following command

$scope.cancel = function () {
  // block = $scope.backUp; <--- this one
  $uibModalInstance.dismiss('cancel');
};

Answer №2

controller: function($scope, $uibModalInstance, block){
    $scope.backUp = angular.copy(block);
    $scope.block = block;
    // the above line does not create new instance of $scope.block instead links to block, so whenever $scope.block gets updated, block also gets updated

Revise Your code as:

HTML :

<script type="text/ng-template" id="myModalContent.html">
    <div class="modal-header">
        <h3 class="modal-title">I'm a modal!</h3>
    </div>
    <div class="modal-body">
        <form class="form-group">
            <input class="form-control" placeholder="Title" type="text" ng-model="data.title" ng-model="titleText" />
            <input class="form-control" placeholder="Main Body" type="text" ng-model="data.body" ng-model="bodyText" />
            <button class="btn btn-success" type="submit" ng-click="saveBlock()"> Save </button>
            <button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
        </form>
    </div>
</script>

Updated ng-model to bind to data object

JS :

$scope.modalUpdate = function (selectedBlock) {
    var modalInstance = $uibModal.open({
        animation: $scope.animationsEnabled,
        templateUrl: 'myModalContent.html',

        controller: function ($scope, $uibModalInstance, block) {
            $scope.data = {};
            $scope.data.title = block.title;
            $scope.data.body = block.body;

            $scope.saveBlock = function () {
                block.title = $scope.data.title;
                block.body = $scope.data.body;
                $uibModalInstance.close($scope.block);
            };

            $scope.cancel = function () {
                $uibModalInstance.dismiss('cancel');
            };
        },
        size: 'sm',
        resolve: {
            block: function () {
                return selectedBlock;
            }
        }
    });
};

Assigned to $scope.block only upon triggering saveBlock, otherwise no action on cancel

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

Consolidate code by implementing on selectmenu

I need assistance with handling multiple select menus on a View page Below is a snippet of the code: $(function() { var selectSpeed = $('#speed'), selectTest = $('#test'); selectSpeed.selectmenu(); selectTest.selectmenu() ...

Requiring addresses for Google Maps in order to display directions

To display the directions between two addresses based on the chosen transportation mode, I need to pass the addresses to the code in page 2. After the user selects two cities from a Dropdown box on page 1, they will be sent to the code to show their locati ...

The npm registry does not contain the package 'angular-fusioncharts'

Upon attempting to add angular-fusioncharts to my package.json file, I encountered the following error message: The 'angular-fusioncharts' package is unavailable in the npm registry. ...

Retrieve octet-stream information from azure eventhub utilizing node.js

I am new to working with Microsoft Event Hub and I have successfully managed to read sample string data from the EventHub using a Node.js consumer. However, I now need to consume octet-stream data. Here is my code: var messageHandler = function (myIdx, ms ...

Pressing a button will reset the input spinner in Bootstrap

Is there a way to reset the bootstrap input spinner by clicking a button? I attempted using document.getelementbyId().value = "0" and also tried using reset(), but neither method worked. Any suggestions on how to successfully reset it? function resetScor ...

Obtain GPS coordinates (latitude/longitude) from a Google map by dropping a marker on the

Is there a straightforward script that can load a Google Map and, when clicked, display a marker that saves the latitude and longitude values to a variable? Does anyone know if there is an existing PHP solution for this functionality? Appreciate any help ...

Is it possible to display a upload progress indicator without using a specialized ajax uploader

I'm working on a Rails application that uploads large files (~300mb). Is there a way to incorporate a progress indicator without relying on a specific HTML5 uploader or installing the nginx server module? Can this be achieved simply with the standard ...

Which slider was featured in the unity3d.com/5 website?

While browsing the internet, I came across the website and was intrigued by the slider effect featured in the "graphics" section. I am eager to figure out how to replicate that stunning visual effect. ...

Modifying Data in Another Component in VueJS

I have a classic Vue Component structured like the following: Vue.component('bar', { template: `<div class="bar"></div>`, data () { return { blocks: [ ] ...

Most effective method for transferring variables from Symfony2 to Angular scope

Like many other developers, I am faced with a common scenario - our mature application is based on Symfony2 / TWIG, and some of the html.twig templates have become overloaded with jQuery code, making them difficult to maintain. I am considering replacing ...

Tips for modifying a request api through a select form in a REACT application

Apologies if this question seems a bit basic, but I need some help. I am working on creating a film catalog using The Movie Database API. I have successfully developed the home and search system, but now I am struggling to implement a way to filter the fi ...

Assign specific classes to the rows and overall table by extracting information from the first row and first column of the table

My goal is to utilize jQuery in order to dynamically assign classes to the rows and columns of a table based on the classes of the first row and column. For instance: The current HTML code I have is as follows: <table class="numAlpha" border="1"> ...

How can I create a hover effect animation in React?

I am looking to replicate the menu item underline animation demonstrated in this example. In jQuery, I would easily achieve this by obtaining the left position and width of a menu item, then using stop.animation on hover. Attempting this animation with R ...

Transforming a jsonObject into a JavaScript array

I am working with a JSON object and I need to extract data from it to create an array. Here is an example of the desired array: ['city 1','city 2','city ..'] Below is the JSON output: {"\u0000*\u0000_data":[{"id": ...

What could be the reason that the close() method is not successfully closing the window that I have generated?

Although there are no error messages, I am encountering an issue where the function windowClose() does not execute when I click on the 'close window' button. Why could this be happening? Take a look at my code below: HTML <!DOCTYPE html> ...

Capture a chart created with chart.js at full screen size across various window dimensions using html2canvas

I am trying to create a PDF featuring images generated by html2canvas. The main component on my webpage looks like this: https://i.sstatic.net/V7RVZ.jpg When I view the generated PDF in fullscreen mode, it appears as follows: https://i.sstatic.net/QW8Ct.j ...

Transform the HTML content into a JSON format file

I'm currently developing an online marketplace and trying to convert all product information like name, price, and description into json format. I have a sample code featuring a selection of products displayed in rows. <div class='cakes'& ...

Sort posts alphabetically by their first letter using jQuery

Currently, I am dealing with a collection of products sourced from WooCommerce and displayed as custom posts through the Elementor page builder at this link: My attempt to incorporate an alphabetical filter using a plugin has not been successful, most lik ...

Creating a Pre-authentication service for AWS Cognito using VueJS

Implementation of Pre-Authentication feature is needed in my VueJS application for the following tasks: Validation of ID/Refresh Token to check if it has expired. If the IdToken has expired, the ability to re-generate it using the Refresh Token or altern ...

The server has restricted access from the local host due to the CORS policy. The request header field for content type is not permitted by

When working with asp.net core 5, I encountered an issue while trying to post data to the database using services. The error I received was related to CORS policy, specifically stating that the request header field 'content-type' was not allowed ...