Maintain modifications in AngularJS modal even after closure

I have an HTML file with some AngularJS code for a modal window.

<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
    <div class="modal-header">
        <h3>I'm a modal!</h3>
    </div>
    <div class="modal-body">
        <ul>
            <li ng-repeat="item in items">
                <a ng-click="selected.item = item">{{ item }}</a>
            </li>
        </ul>
        Selected: <b>{{ selected.item }}</b>
    </div>
    <div class="modal-footer">
        <button class="btn btn-primary" ng-click="ok()">OK</button>
        <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
    </div>
</script>

<button class="btn btn-default" ng-click="open()">Open me!</button>
<div ng-show="selected">Selection from a modal: {{ selected }}</div>

In addition, there is JavaScript code managing the modal functionality.

var ModalDemoCtrl = function ($scope, $modal, $log) {

$scope.items = ['item1', 'item2', 'item3'];

$scope.open = function () {

var modalInstance = $modal.open({
  templateUrl: 'myModalContent.html',
  controller: ModalInstanceCtrl,
  resolve: {
    items: function () {
      return $scope.items;
    }
  }
});

modalInstance.result.then(function (selectedItem) {
  $scope.selected = selectedItem;
}, function () {
  $log.info('Modal dismissed at: ' + new Date());
});
};
};

var ModalInstanceCtrl = function ($scope, $modalInstance, items) {

$scope.items = items;
$scope.selected = {
  item: $scope.items[0]
};

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

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

I would like to know how to retain changes made when clicking the cancel button and then reopening the window. For a live example, you can visit http://angular-ui.github.io/bootstrap/#/modal.

Answer №1

Is it effective? Can you transmit items using $modalInstance.close();

(Plunkr: http://plnkr.co/edit/Lbwz5K3Wg8ivp9tBK7Bb?p=preview)

angular.module('sample', ['ui.bootstrap']);
var ModalDemoController = function ($scope, $modal, $log) {

  $scope.items = ['item1', 'item2', 'item3'];

  $scope.openModal = function () {

    var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: ModalInstanceController,
      resolve: {
        items: function () {
          return $scope.items;
        },
        selectedItem : function() {
          return $scope.selectedItem;
        }
      }
    });

    modalInstance.result.then(function (selectedItem) {
      $scope.selectedItem = selectedItem;
    }, function (selectedItem) {
      $scope.selectedItem = selectedItem;
      $log.info('Modal dismissed at: ' + new Date());
    });
  };
};

// Remember that $modalInstance is for a modal window instance dependency and is not the same as the $modal service above.

var ModalInstanceController = function ($scope, $modalInstance, items, selectedItem) {

  $scope.items = items;
  $scope.selectedItem = {
    item: selectedItem || $scope.items[0]
  };

  $scope.okay = function () {
    $modalInstance.close($scope.selectedItem.item);
  };

  $scope.cancelled = function () {
    $modalInstance.dismiss($scope.selectedItem.item);
  };
};

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

The testing for React and TypeScript did not succeed. It is recommended to utilize the "jsdom" test environment for better results

I'm working on a basic React/TypeScript project and diving into the world of testing. I've opted for React Testing Library and Jest to test a straightforward product page that should display the message "Welcome to our product page." Unfortunate ...

Tips for displaying and concealing objects within dynamic rows using AngularJS

I'm relatively new to working with AngularJS and I've run into a bit of a roadblock. I have created a custom directive to apply a function and pass in the row index, but I'm struggling to figure out the best way to display items in a row. Ho ...

Identifying the specific promise that failed within a chain of .then statements

I am currently working on setting up a chain of promises with an error catch at the end within my node and express application. One issue I have encountered is that if any of the 'then' functions encounter an error, it can be difficult to trace b ...

Issue with jquery curvy corners not functioning properly on Internet Explorer 8

Check out my website at If you view the page in IE8 and then in IE7 compatibility mode, you'll notice a strange issue. The box on the right disappears in IE8 but displays perfectly rounded corners in IE7. I am currently using the jQuery Curvy Corner ...

Instantly magnifying on the initial point regardless of the zoom type chosen is a feature of Chart.js zoom

Despite adding zoom functionality to my line chart, I am facing an issue where it automatically zooms in to the first point and does not allow me to zoom back out, except for using the reset zoom function. The zoom out function is also not working properly ...

What is the process of initializing divs in DataTables?

My application has a DataTable installed, but I encountered an error message stating "DataTables warning: Non-table node initialisation (DIV). For more details about this error, please visit http://datatables.net/tn/2". I'm aware that DataTables is d ...

Is the output returning before the AJAX call is completed?

Similar Question: How can I get the AJAX response text? When calling a JavaScript method that sends an Ajax request and receives a response in a callback function labeled "success," sometimes the JavaScript method returns a result as "undefined" inste ...

When the Model popup is activated, it is essential for elements to have an adequate color contrast

Our team is utilizing the axe dev tool for accessibility testing. We encountered an issue where elements behind a model popup (Kendo React model with position: absolute) were displaying insufficient color contrast errors. Upon changing the absolute positio ...

Iterate through an ajax function by employing promises

I have recently delved into the world of es6-promises and I'm struggling to fully grasp its concepts. In my project, I am attempting to retrieve data through an ajax call and keep looping until all data is fetched (essentially pagination). Below is t ...

The request for JSON parsing encountered a failed attempt, resulting in an error while trying to parse the JSON

var userData = { "emailAddress": document.getElementById('emailAddress').value, "password": document.getElementById('password').value } var userDataString = JSON.stringify(userData); alert(userDataString); var url = "url"; var ...

Download a complete website using PHP or HTML and save it for offline access

Is there a way to create a website with a textbox and save button, where entering a link saves the entire website like the 'save page' feature in Google Chrome? Can this be done using PHP or HTML? And is it possible to zip the site before downloa ...

Express.js: Initial Request Fails to Retrieve Set Cookie

In my Express.js application, I am facing an issue where setting a cookie in one middleware function results in it being undefined when attempting to access it in the following middleware function on the initial request. Strangely, on subsequent requests, ...

What does the client perceive or not perceive? Node.js, JavaScript, MySQL

For a university project, I am tasked with creating a web application that is compatible with both desktop browsers and mobile devices. The technologies I will be using include HTML, CSS, JavaScript, Node.js, and MySQL. I have recently familiarized myself ...

Transfer razor javascript calls in Blazor WebAssembly to a separate class

Scenario Description Greetings, I am currently working on a Blazor WebAssembly project that involves JavaScript interop. Initially, I had this functionality working in a .razor page. However, I now intend to encapsulate and centralize these JavaScript inv ...

Error: Kinetic.js cannot upload image to canvas

There must be something simple that I'm missing here. I've checked my code line by line, but for some reason, the image just won't load. var displayImage = function(){ var stage = new Kinetic.Stage("imgarea", 250, 256); var layer = new ...

The method item.appendChild does not exist as a function

Despite being a common error, I've researched extensively and still can't figure out why it's happening. It seems like it should be an easy fix, but I'm struggling to find the solution on my own. var item = document.createElement("div" ...

Guide on capturing every error thrown in a Vue.JS single-page application

As I develop a web application, my goal is to effectively capture any errors that may occur throughout the entire Vue.js web app. Although I investigated the errorHandler, I discovered that it only catches errors during rendering or watching processes. Th ...

Maximizing Efficiency: Utilizing a Single Panel across Multiple HTML Files with jQueryMobile

Can a panel defined in index.html be used on another page, such as results.html? Or do I have to define the panel on every page and duplicate the HTML code on each page? Because I want the panel to be consistent across all pages. This is the panel in my ...

Issues arise with loading AngularJS directive properly within the context of service utilization

Currently, I am diving into the world of JavaScript and tackling a project that involves fetching data from MongoDB. My task is to write code in AngularJS to create a pie chart using Highcharts. Surprisingly, everything works smoothly when I solely use an ...

Place the image either above or below the text in a relative position

I have a peculiar dilemma that has been on my mind lately. As I work on designing my website, I am nearing completion of the responsive/mobile view. Currently, everything looks fine, but only because I use display: none; to hide images when the viewport is ...