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

Discovering instances of a specific string within a larger string

My goal is to customize the default behavior of the alert function. Below is the code I am using: window.alert=function(txt) { waitOk='wait'; setMsgBox(txt); btnMsgOk.focus(); } However, I need this functionality to vary ba ...

Angular Ladda button is inactive and unresponsive, indicating it is not functioning

Having trouble with angular-ladda as I'm only getting a blank button instead of the spinner icon: https://i.stack.imgur.com/8wWs6.png All CSS and modules are loaded correctly. This is the HTML code being used: <button ladda="news.working" class ...

Utilize AngularJS to refine and sort through data retrieved from an API

I have an Angular application that is fetching hotel data from an API. I want to filter the results based on the minimum price of the hotels being less than $50. $http.get($rootScope.baseurl + 'api/hotels/', { params: { page_ ...

How can a JSON string be assigned to a variable for use in a Google pie chart?

I am currently experiencing an issue with my web server. I am sending a JSON object as an argument via render_template to my website, where I intend to use this data to display a Google pie chart. The problem arises when I try to assign the Google pie cha ...

Tips for Transferring Values Between Multiple Dropdown Menus with jQuery

Hello there, can anyone guide me on how to transfer selected items from one multiple combo box to another multi-combo box? I would really appreciate it if someone could provide an example for this scenario. <HTML> <HEAD> <TITLE></T ...

Utilizing Local Storage in Vuex Store with Vue.js

I have been working with localStorage for storing and retrieving items in my JavaScript code housed within a .vue file. However, I am now looking to find a way to transfer this stored data into my Vuex store, specifically within the mutations section locat ...

Tips for Retrieving Html Element Attributes Using AngularJS

Update: Even though the discussion veered off track, the main question still stands - how can I access an attribute of an HTML element within an Angular controller? Check out my attempt on Plnkr: http://plnkr.co/edit/0VMeFAMEnc0XeQWJiLHm?p=preview // ...

What strategies can I implement to prevent the JavaScript CallStack from becoming overloaded?

The code snippet below outlines the functionality achieved through JavaScript (specifically for a node.js COMET application): A request is sent to the server and held until there is a response. Upon receiving a response, the data is processed, and anothe ...

Incorporate External Web Page Information by Clicking a Button

Apologies if this question has already been asked, but despite my efforts to explore the available resources, I have not found a solution to my issue. I currently have an input field where users can enter their website, keyword, or industry. When they cli ...

Chai-http does not execute async functions on the server during testing

In my app.js file, there is a function that I am using: let memoryCache = require('./lib/memoryCache'); memoryCache.init().then(() => { console.log("Configuration loaded on app start", JSON.stringify(memoryCache.getCache())); }); app.use( ...

A guide on how to initiate a click event in Angular 5 using JQuery

I am trying to trigger a click event for each element based on its id, but it doesn't seem to be working. Below is the code I am using: ngOnInit() { this.getProductsLists(); } getProductsLists() { this.supplierService.getProductLists() .sub ...

Jest throws an error: require function is not defined

I've been struggling with an issue in Angular for the past 3 days. I'm using [email protected] and [email protected]. I even tried downgrading and testing with LTS versions of node and npm, but I keep encountering the same error. Here ...

Alter the content of a div depending on the values of three different elements

Hello everyone, I am new to the world of jQuery and javascript, and I am facing a challenge that I need some help with. Within a form, there are two fields that I would like to perform calculations on. Here is what I have attempted so far: jQuery.fn.calcu ...

The width of the Bootstrap row decreases with each subsequent row

I'm having trouble understanding this issue, as it seems like every time I try to align my rows in bootstrap, they keep getting smaller. Can anyone point out what mistake I might be making? ...

What is the best method for testing routes implemented with the application router in NextJS? My go-to testing tool for this is vitest

Is it possible to test routes with vitest on Next.js version 14.1.0? I have been unable to find any information on this topic. I am looking for suggestions on how to implement these tests in my project, similar to the way I did with Jest and React Router ...

Using a React component to send data through a POST request to an API

When attempting to send a selected value from a Dropdown to an API using a POST request, I keep encountering a 405 (Method Not Allowed) error. Despite trying different ways to handle the onChange event, such as: onChange{(e) => this.onChangeHandler(e.t ...

What methods can we employ to prevent the GraphQL query from being triggered with every keystroke when using React?

Recently, I received a new task that requires me to implement input value debouncing to prevent backend requests on every keystroke. Additionally, I need to establish an internal useState for CollectionsAutocomplete, which is connected to the generalQuery ...

Can one request a service method that includes the `fromParams`?

Are there any options available for retrieving an object, such as a service, that contains the stateParams from the prior state? I understand that I can access them during the $stateChangeStart event, and while that works, I would prefer to avoid redunda ...

What's a way to pass a PHP variable directly to Javascript without using AJAX?

In my setup, I've implemented a JavaScript code that validates and sends the 'artwork' file to a PHP script on my server. This PHP script also performs its own checks for redundancy before writing the file to /uploads directory. The challen ...

Mapping objects in an array with Javascript

This code snippet is intended for a React Native Chat app. The structure of my data should look something like this: const chatData = [ { id: 1, name: 'John Doe', messages: [ {text: 'Hello', sentAt: 'time here' ...