Angular UI directive for modal confirmation

Looking to create a custom Angular directive using angular-bootstrap that mimics the confirm() function.

Check out the visual result and desired behavior in this plunk: http://embed.plnkr.co/27fBNbHmxx144ptrCuXV/preview

Now, I want to implement a directive to trigger the modal window:

<div ng-controller="ModalDemoCtrl">
     <ul>
         <li ng-repeat="item in items">
              {{ item }} <a ng-really-message="Are you sure ?" ng-really-click="reallyDelete(item)">Delete</a>
         </li>
     </ul>
</div>

I have managed to create a functional directive using the 'confirm()' function. However, when attempting to switch to the modal window instead of confirm, an error "$digest already in progress" is encountered.

Here's the plunk for reference: http://plnkr.co/edit/JSOInyZIvMtBZFaNvQRO?p=preview

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

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

  $scope.reallyDelete = function(item) {
    $scope.items = window._.remove($scope.items, function(elem) {
      return elem != item;
    });
  };
};

angular.module('ngReallyClickModule', ['ui.bootstrap'])
  .directive('ngReallyClick', ['$modal',
    function($modal) {

      var ModalInstanceCtrl = function($scope, $modalInstance) {
        $scope.ok = function() {
          $modalInstance.close();
        };

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

      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
          element.bind('click', function() {
            var message = attrs.ngReallyMessage || "Are you sure ?";

            /*
            //This works
            if (message && confirm(message)) {
              scope.$apply(attrs.ngReallyClick);
            }
            //*/

            //*This doesn't work
            var modalHtml = '<div class="modal-body">' + message + '</div>';
            modalHtml += '<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>';

            var modalInstance = $modal.open({
              template: modalHtml,
              controller: ModalInstanceCtrl
            });

            modalInstance.result.then(function() {
              scope.$apply(attrs.ngReallyClick); //raise an error : $digest already in progress
            }, function() {
              //Modal dismissed
            });
            //*/

          });

        }
      }
    }
  ]);

I

Answer №1

Utilize function binding with AngularJS:

scope:{
    ngReallyClick:"&", //function binding for directive
    item:"=" //current item for the directive
},

Your HTML code:

<a ng-really-message="Are you sure ?" ng-really-click="reallyDelete(item)" item="item">Delete</a>

Invoke your function upon user confirmation:

modalInstance.result.then(function() {
     scope.ngReallyClick({item:scope.item}); //invoke function through binding
}, function() {
              //Modal dismissed
});

DEMO

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

Using AngularJS's ng-repeat to dynamically display JSON data

I am facing an issue extracting data from ng-repeat. <tr ng-repeat="x in records"> <td>{{x.id}}</td> <td>{{x.title}}</td> <td>{{x.year}}</td> <td>{{x.note}}</td> </tr> The value ...

Integrating AngularJS into the Bitnami MEAN stack platform

Despite successfully activating all the JS programs for the MEAN stack, I am facing issues with Angular. I have attempted to understand the process of creating .bowerrc in my application directory, but it's proving challenging. Following the instruc ...

Move a div by dragging and dropping it into another div

Situation Within my project, there is a feature that involves adding a note to a section and then being able to move it to other sections, essentially tracking tasks. I have successfully implemented the functionality to dynamically add and drag notes with ...

Is it Appropriate for Custom React Hooks to Trigger Re-Render of Related Components?

I have just developed a custom hook that internally uses useState and useEffect. After importing this hook into another React function component called ComponentA, I noticed that ComponentA re-renders every time the state within the custom hook changes. ...

Exploring the use of functions in the setup method of Vue 3

I'm currently working on a simple app and utilizing mock-json-server to mimic http requests. Within my project, I have defined a function designed to retrieve the necessary information: import { ref } from 'vue' const getScores = () => ...

Tips for preserving drop down selections when refreshing the page

I am currently working on a program with 2 drop-down menus and 2 buttons. My goal is to have the first button disabled and second enabled when both dropdowns are selected and the "start" button is clicked. Additionally, I want the dropdowns to be disabled ...

Does JSON have a special reserved key for identifying the time?

I've noticed an interesting issue when logging the json string of a key labeled tid - it always shows up as 0. Take a look at this example: var transaction = {tid:1, type:0, time:126312736}; var transStr = JSON.stringify(transaction); console.log(tra ...

Data obtained from the server includes JSON objects along with quotes and regular expressions

While analyzing the functionality of a search page server through element inspection, it was observed that requests are sent via POST with JSON parameters. To verify this observation, I recreated the same POST request using Insomnia with identical paramete ...

Combining NodeJs with Mysql for multiple queries using a chained method

Hey everyone, I'm struggling with running mysql queries repeatedly in my Node.js application. I need to shape the second query based on the results of the first one. The code example I have below is not working as expected. Can anyone provide guidance ...

AJAX Username verification failing to validate

Working with PHP and MySQL, I created a basic form which includes a textfield for the username and a submit button. The page is named checkusername.php. Additionally, I implemented an AJAX function for handling this process. Subsequently, there is another ...

An element in CSS that has a position of fixed and a width of 100% surpasses the dimensions of its

My element has the CSS properties position:fixed and width:100%, causing it to be larger than its parent elements. Despite the complexity of my code, I have attempted to simplify it for better understanding. Below, you can see that the green box exceeds ...

Showing list data from script to template in vue - A step-by-step guide

My task involves displaying data from the main table in MySQL. I need to show the type of each major by comparing it with the id in the faculty table. I have successfully logged this information using console.log, but I'm unsure how to display it on t ...

Trouble with recognizing nested functions when calling them in an onClick event

Encountering a `not defined` error on the console when attempting to call nested functions with an `onClick` event in an HTML page. After searching for solutions without success, I suspect it may be a scope or closure issue, but I am unsure of how to addre ...

There seems to be an issue with posting JSON data correctly

Currently, I am attempting to include an object with numerous attributes within it. This is the object I am trying to use with $.post: ({"fname" : fname, "lname" : lname, "gender" : gender, "traits" : { "iq" : inte ...

Can React-Select be utilized in the browser directly from the CDN?

Is it possible to utilize react-select directly in the browser without using bundlers nowadays? The most recent version that I could find which supports this is 2.1.2: How to import from React-Select CDN with React and Babel? In the past, they provided r ...

The order of key:value pairs in documents created by Mongoose does not always align with the schema

Having trouble understanding how the Mongo .create and .findAndUpdate operations work. My mongoose version is 5.4.2X and I have a model with a schema containing multiple key:value pairs in a specific order (using 1. 2. 3. etc to indicate the correct order) ...

"Displaying 'Object Object' as a title when hovering over an element

I am currently using an accordion element to display several FAQs on a webpage. The code snippet for the accordion with content is as follows: { Object.keys(FAQS).map((key, index) => { return ( <div key={key}> ...

A guide on implementing input tags through instant search in HTML using AngularJS

As someone new to Angular JS, I am working on adding input tags by clicking from instant search using Angular JS. I came across a helpful example of instant search in action through this demo that Google provided. Now, I want to implement the ability to a ...

What is the best way to modify a current state object without causing an endless loop of redirects?

const useCase = (argument) => { const [value, setValue] React.useState(argument) React.useEffect(() => setValue({...value ...argument), [argument, value, setValue]) } The above code is currently causing an infinite loop due to setting the stat ...

JavaScript - Removing Content from an Element

I have a coding script that adds an image preview of uploaded images. The issue I am facing is that the previous image does not clear when the form is filled out again. The id of the div where thumbnail images are being displayed is "thumbnail". Can someo ...