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

Fetching post value via AJAX in Codeigniter views: A step-by-step guide

Having issues receiving Ajax response as it is coming back null. The HTML layout includes: <form method="post" action="<?php $_SERVER['PHP_SELF'] ?>"> <select class="form-control" class="form-control" id="choose_country"& ...

The time zones between Node 8 and Node 11 are not the same

Executing a basic new Date().toString() command produces different results on Node 11 compared to Node 8. In Node 11, the output includes the full timezone abbreviation like this: 'Fri May 10 2019 10:44:44 GMT-0700 (Pacific Daylight Time)' On t ...

Disable the draggable feature upon clicking the button

I am currently working on a code challenge where I need to disable the draggable functionality of all divs styled with .myDivs when the user clicks the 'Remove Draggable' button. You can view my progress in this JSFiddle: http://jsfiddle.net/adri ...

Having trouble displaying information in JavaScript after using getScript() to retrieve data from an API containing a JSON block database

I'm a newcomer to the world of Ajax/json/jquery and I find myself with a few inquiries. Currently, I am working with an API located at which contains a JSON block that looks something like this [{"id":"1","FirstName":"Micheal","LastName":"Kooling"}, ...

Is there a way to transform a large gltf file into jsx format?

I recently created a 3D scene in Blender and wanted to incorporate it into my React Three Fiber project. However, after exporting the scene to glTF format, I discovered that the file contained around 300k lines. The strange thing is that the file works per ...

In JavaScript with Node.js, how can one verify a file's size and only download the initial kilobyte of the file?

When using Javascript/Node JS to download a file, you can check the file size and download only the first kilobyte of the file. This is useful if you want to hash the first kb and compare it with the hash of the complete file. If the hashes match and the ...

Creating a hierarchical JSON format for a nested commenting system

I have a JSON data representing a multi-level comment system as shown below: [{ "thread_id": 2710, "parent_id": "", "username": "string", "comment": "string", "postdate": "2017-06-09T07:12:32.000Z", "id": 1 }, { "thread_id": 2710, "parent_ ...

The value of $parent.$index will consistently be 0 in all cases

I am currently dealing with a nested ng-repeat situation where I am attempting to determine the parent's index. Due to the fact that it is being arranged post-process, the standard ng-repeat="(step_index, step) in flow" method is not working for m ...

Alter the value of a key within a JSON object at a specific nested level using Node.js or JavaScript

I am attempting to swap out a specific value in the JSON file. Let's say the JSON data provided below: sample.json let sample={ "yuiwedw":{ "id":"yuiwedw", "loc": "ar", "body":{ "data":"we got this", "loc":"ar", "system":{ ...

Creating images with LibCanvas

Currently, I am utilizing LibCanvas for canvas drawing on my HTML page. However, I am facing difficulty in drawing an image. Can someone provide assistance with this? UPDATE: The code snippet I am using is showing the image being drawn but then it disappe ...

Checking the content of a textfield in React Material UI based on the user input

Hello! I am seeking a solution to trigger an error message whenever the value entered in the first text field is not equal to "28.71", otherwise display a correct message. Here is my current code: class Main extends React.PureComponent { render() { ...

Employing ng-repeat within a ui-scope

I'm having trouble getting my ui-view to update dynamically using ng-repeat. I'm not sure if what I want to do is even possible because when I add static objects to intro.html, they display properly. Thank you for any assistance, JS }).st ...

Angular View receives OAuth Token Response via Cookie

I've been tackling this issue for a couple of hours now and could really use some assistance. I created a basic app that displays a "Login Using Google" button in an Angular view, which then redirects the user to the Google OAuth page. Below is the co ...

Is it possible to link the value of an input[range] to an array?

I want to create an array called arr dynamically with a length based on the value of ng-model (numberFloor) from an input[type=range]. var app = angular.module("houseBuilder", ['ngSanitize']); app.controller('myCtrl', function($scop ...

Assign the textbox's value to be the earliest selected date from the datepicker

Can anyone assist me? I have a working code that activates only the specific day of the week I want on the datepicker. However, the textbox doesn't have a default value and I would like it to display the first date activated in the datepicker. In th ...

Error message stating that the function "data.map" is not recognized, resulting in a

const ShoppingList = ({ itemList }) => { let { loading, items } = itemList; console.log(items); return ( <div> {loading ? ( <p>Loading...</p> ) : ( <table> <thead> ...

Get the data from the files in the request using request.files in Node.js

Is there a way to read the content of a file (either a txt or CSV file) that a user uploads without saving it to local storage? I know I can save the file in an upload directory and then read it from storage. However, I'm wondering if there is a way ...

Does CSS in the current IE9 beta allow for text shadows to be implemented?

Text shadows look great in Firefox and Chrome. For example, I have a basic website for streaming videos. Unfortunately, there are no shadows in IE9 for me. This is my CSS code: p { color: #000; text-shadow: 0px 1px 1px #fff; padding-bottom: 1em; } ...

The tagging feature in ui-select isn't working properly, showing an error message that says "Cannot read property 'length' of undefined"

Looking to set up a ui-select for keyword tagging. Initially, when adding a new tag everything works fine, but after removing all tags and adding a new one, I get the error: Cannot read property 'indexOf' of undefined Check out the demo here ...

Is it possible to simultaneously use two $scoped variables within an Angular controller?

Currently, I am developing an angular application that connects to a Rails backend and interacts with the database through API calls to receive JSON objects. My challenge lies in defining multiple scoped variables within a controller. At the moment, I have ...