The save and cancel button are experiencing technical difficulties and are currently non-functional

After creating an application in AngularJS to add and remove popup modals, I encountered an issue where the saved data was returning as undefined, and the cancel functionality was not working properly.

Check out the JSFIDDLE here

If anyone has any solutions or suggestions for this problem, please do let me know.


        // AngularJS code goes here
        // More code....
    

Answer №1

Here

View the Working Demo for $rootScope

Check out the Working Demo for Factory Version

The issue arises when controller scopes like mainController and ModalInstanceCtrl have their own unique scope instances, not sharing the same scope across the app. Utilizing $rootScope as a global object can lead to poor design practices.

In the first working demo, the $rootScope variable is being used. However, dependence on a global object is not advisable.

To facilitate communication between controllers, it's recommended to create a factory service such as userFactory and pass it between your controllers. Within the factory service, manage your modals.

Insert revised code with modifications here...

Answer №2

It is crucial to reference the modalInstanceController when creating a modal, rather than the mainController.

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

Remember to pass the resolutions into the controller parameters as well, and utilize the methods like close and dismiss from the $modalInstance service...

commonApp.controller('ModalInstanceCtrl', function ($scope, $rootScope, $modalInstance, usersInModalScope, deptInModalScope) {
    $scope.cancel = function () {
        $modalInstance.close();
    }

    $scope.save = function () {
        alert(JSON.stringify($scope.selectedUsers));
    }
});

While your implementation may not work as expected, consider using this version for ui.bootstrap and modals.

ProductsCtrl

angular.module('app', ['ui.bootstrap'])

.controller('AppController', function($scope, $modal, $templateCache) {

  $scope.product = { product: 'I am the product' };

  $scope.openEditProductModal = function () {

    var editProductModal = $modal.open({
        templateUrl: 'edit-product.html',
        controller: 'EditProductModalController',
        resolve: {
            product: function () {
                return $scope.product;
            }
        }
    });

    editProductModal.result.then(function (product) {
        $scope.product = product;
    });
  };


})

Modal Controller

.controller('EditProductModalController', function ($scope, $modalInstance, product) {

   $scope.product = product;

   $scope.ok = function () {
            /**
             * Set the edited description and close the modal resolving the promise
             */
            $scope.product = product
            $modalInstance.close($scope.product);
        };

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

    })

HTML

  <body ng-controller="AppController">
      <h1 ng-bind="product.product"></h1>
      <br>
      <button ng-click="openEditProductModal(product.product)">Open Modal</button>
      <br>
      <span ng-bind="product.product"></span>
  </body>

Edit-Product.html

<div class="modal-header">
  <h3><span class="glyphicon glyphicon-edit"></span> Edit Product</h3>
  <span class="subtitle" ng-bind="product.name"></span>
</div>
<div class="modal-body edit-description-modal">
  <div class="row">
    <input ng-model="product.product"/>
  </div>

</div>
<div class="modal-footer">
  <button class="btn btn-primary" ng-click="ok()">Save</button>
  <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>

Visit Plunkr for more details.

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 website is plagued by the presence of unwanted hyperlinks

There seems to be unwanted hyperlinks appearing in the text content on my website. Website URL: http://www.empoweringparents.com/my-child-refuses-to-do-homework-heres-how-to-stop-the-struggle.php# Could you please review the 10th point? There are links b ...

Run an anonymous function when the page is loaded

When it comes to loading a JavaScript function upon page load, there are various methods such as onLoad(), $( document ).ready(), and more. However, I am facing an issue with a function that does not have a specific name. This unnamed function is used to ...

building responsive servers within Gulp using connect

Can I validate the availability of a server port before creating it using Gulp? Currently, this is my approach: /** * Start LiveReload Server */ gulp.task('connect', function() { var connect = require('connect'), app = ...

Rails confirmation feature malfunctioning

I have been struggling to figure out where I am going wrong with this code even though I've checked several posts. I am using Ruby on Rails and trying to run the following snippet: <%= link_to 'Destroy', article_path(article), ...

Tips for implementing two functions to run within the onClick event handler in React

I am looking to simultaneously execute two functions handleClose and saveData within the onClick method. The specific location where I want this execution to happen: <Button variant="contained" onClick={saveData}&g ...

The exportAs attribute is not specified as "ngForm" for any directive

Encountered an error while attempting to test the LoginComponent PhantomJS 2.1.1 (Linux 0.0.0): Executed 3 of 55 (1 FAILED) (0 secs / 0.307 secs) PhantomJS 2.1.1 (Linux 0.0.0) LoginComponent should create FAILED Failed: Uncaught (in promise): Error: Templ ...

I am seeking assistance with generating a printed list from the database

Struggling for two full days to successfully print a simple list from the database. Take a look at the current state of the code: function CategoriesTable() { const [isLoading, setLoading] = useState(true); let item_list = []; let print_list; useEffect(( ...

No results found: AngularJS typeahead feature does not display search results when there is no match for the inputted text

I'm currently utilizing Angular UI-bootstrap typeahead component. In my HTML file, I have: <input type="text" ng-init="selectedCrossFormFieldText = selectedCrossFormFieldText || {}" ng-model="selectedCrossFormFieldText[fieldId]" ...

Issue with PHP's ng-click not functioning properly with Angular JS's dynamic HTML generation

I'm just starting out with Angular JS. I'm trying to create an ng-click event in dynamically generated HTML from PHP, here's the code snippet. var app = angular.module('pageapp',[]); angular.module('pageapp') .filter(& ...

Initializing JavaScript prior to registering the Polymer element

When upgrading from Polymer version v0.5 to v1.0, the process of registering Polymer elements seems to have changed. Previously, in Polymer v1.0, we were able to execute JavaScript code from the index.html file to initialize all the necessary objects in ou ...

Tips for enabling a keypad to restrict input field character limit

Encountering an issue with an input field that has a maximum length of 6 characters. Typing normally seems to work fine, but when using a custom keypad, the limit is not enforced and it allows for more than 6 characters to be entered. HTML: <div cl ...

Utilizing Node.js (Express) to import a JSON file from StackExchange and display the data

I've been working on a task to retrieve a json file from the stackexchange api and store it on the client side once the server loads, allowing me to make local changes to it. Despite my efforts, the page just continues loading without any results. He ...

Utilizing regex patterns within Jqgrid

I am currently utilizing the JqGrid plugin (version 4.6.0 - jQuery Grid) to filter my results using specific fields. Here is an example of how the GUI appears: https://i.sstatic.net/BqGai.png With a large list of employees, I want the ability to filter t ...

Struggling to display a chart using angular-chart

I am facing an issue with rendering my chart. I have followed the instructions provided on the GitHub page of angular-chart.js. I have created a plunker to showcase my problem: http://plnkr.co/edit/x7XJhxxvYMzWr3u7lBcJ?p=preview Although I can access and ...

How to implement the ECharts animated bar chart in Angular version 16?

The animated bar chart in ECharts functions perfectly on Stackblitz. You can check it out here in the Stackblitz Angular 16 demo. However, attempting to run the same demo in a local Angular 16 project led to the following errors. Error: src/app/animated- ...

Choose a jQuery Add-on

Does anyone know of a jQuery plugin that can achieve the functionality displayed in the image below? I'm looking for something where users can select one or more options, similar to tags. Each option must contain its own unique ID. (In the future, I ...

Yii: Error: The method 'typeahead' is not defined for the object [object Object]

I am currently working on a project using Yii and I encountered a small issue with the Typeahead widget from Yiistrap. It seems that jQuery is being included multiple times - twice before the inclusion of bootstrap.js and once after. Uncaught TypeError: O ...

Using Flexbox CSS to Expand a Box According to its Content Size, Without Impacting Adjacent Rows

Is there a way to make the bottom-most row (highlighted in yellow) expand downward to fill available space? Check out this link for reference: https://jsfiddle.net/darrengates/oucvnfke/ I initially thought using: flex: auto; would solve the issue. Whil ...

Tips for sending a message to multiple servers

As a Discord.js developer, I am facing an issue with sending a message to all guilds/servers that my bot is in. Previous solutions provided were for outdated versions and do not work anymore. Can anyone offer assistance? The following code snippet does n ...

Validate if cookie has been established in Javascript

Hello everyone! I am trying to redirect a user to another page when a cookie is set by clicking a button. <a href="" onClick="SetCookie('pecCookie','this is a cookie','-1')"><button type="button" name="accept" clas ...