Toggle the flag status of a checkbox based on the response provided in dialogues (Angular)

Query: I am facing an issue with my checkbox system where a dialog pops up when trying to unflag a form by unchecking the box. The dialog asks for confirmation before removing the form. How can I ensure that the checkbox remains checked until the user clicks "Confirm" or "Cancel"? And how do I keep it checked if the user selects Cancel, and unchecked if they choose Confirm?

Below is the relevant code snippet:

file.js (contains angular module, controllers, etc.):

... //INSIDE controller 'ctrlOne'
$scope.fromService = dialog.deletionConfirmDialog('Title','Wanna remove?');
...
//OUTSIDE controller 'ctrlOne'
...

...
hello.service('dialog', function($mdDialog) {
   this.deletionConfirmDialog = function(title, cont){
        $mdDialog.show($mdDialog.confirm({
            templateUrl: 'deletionConfirmDialog.html',
            title : title,
            textContent : cont,
            ok : 'Confirm',
            cancel: 'Cancel'
        })).then(function() {
             console.log('confirmed');
             //to be completed
        }, function() {
             console.log('abort');
             //to be completed
        });
    }
}
...

stepOne.html:

...
  <div ng-repeat="item in serv" ng-model="item.active">
      <md-checkbox id="{{item.id}}" aria-label="check" type="checkbox">                      ng-model="item.attivo">
 </div>
...

The stepOne.html page is linked to a specific controller ('ctrlOne').

Answer №1

If you want to experiment with the ng-checked directive, here's a way to do it:

Create a service like this:

hello.service('dialog', function($mdDialog, $q) {
var deferred = $q.defer();
   this.deletionConfirmDialog = function(title, cont){
        $mdDialog.show($mdDialog.confirm({
            templateUrl: 'deletionConfirmDialog.html',
            title : title,
            textContent : cont,
            ok : 'Confirm',
            cancel: 'Cancel'
        })).then(function() {
             console.log('confirmed');
             //to be completed
deferred.resolve();
        }, function() {
             console.log('abort');
             //to be completed
deferred.reject();
        });

return deferred.promise;
    }
}

Incorporate the following in your HTML:

<div ng-repeat="item in serv" ng-model="item.active">
      <md-checkbox ng-checked="tempFlag" id="{{item.id}}" aria-label="check" type="checkbox"ng-model="item.attivo" ng-change="changeFunc()">
 </div>

In your controller:

if($scope.item.attivo)
      $scope.tempFlag = true
else
      $scope.tempFlag = false;

$scope.changeFunc = function() {
    dialog.deletionConfirmDialog('some title', 'some content').then(accept, reject)

function accept() {
    $scope.tempFlag = !$scope.tempFlag;
};

function reject() {
     $scope.item.attivo = !$scope.item.attivo;
}

}

Answer №2

Consider implementing the following approach:

<input onchange="checkChange()" type="checkbox" id="myCheckbox">
<script>
function checkChange()
{
alert("The checkbox was unchecked!");
}
</script>

Alternatively, you can incorporate an onclick event for the confirmation button to identify any unchecked boxes and prompt the user to double-check their choices.

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

Mastering the art of crafting and managing NodeJS promises with finesse

Currently, I am utilizing ExpressJS for handling APIs and heavily rely on promises for managing asynchronous requests such as external API calls and database queries. While this approach works well in most cases, it tends to clutter the code with numerous ...

Looping through AJAX requests in JavaScript

I am attempting to make REST API requests in order to retrieve data and display it on a website. Although I have created a for loop to gather the data, I am encountering an issue where the data is not being displayed on the website. Upon checking with th ...

Tips for determining the time and space complexity of this JavaScript code

Here are two codes utilized by my platform to establish relationships between nodes. code1 : const getNodeRelationship = (node1, node2) => { // if node1 and node2 are the same node if (node1 === node2) return null; // check direct parent ...

Can I monitor when a $http request is being processed?

One of the functions in my service is as follows: self.$http({ url: xxx, method: "DELETE" }) .success((): void => { }); I am looking for a way to dynamically disable a button on my html page while the $http call is being made. Is there a sol ...

Locate and substitute `?php` and `?` in a given string

I am facing a challenge with inserting a large string of valid HTML code into the DOM, as the string also includes PHP code. When Chrome renders the code, it automatically comments out the PHP sections. The PHP code is encapsulated in <?php ... ?>, s ...

Exploring Angular 2 Application Testing: Tips for Interacting with HTML Elements

In my Angular 2 Frontend testing journey, I came across a blog post ( ) where the author utilized ng-test TestBed for core testing in Angular. While the example provided was helpful for basic understanding, it lacked details on how to manipulate Elements. ...

Upgrading to React Router v6: Implementing Loader Functions with Context API

Having issues implementing loaders in React-Router V6 while making a request for a page through a function located in the context file. Unfortunately, I can't access the context from main.js where the router is defined. Main.js import ReactDOM from & ...

Modify the text highlighted in bold within the AngularJS application

In my angular.js application, I have a table that displays elements. The name of these elements sometimes needs to be displayed in bold by adding <b> and </b> tags. However, instead of rendering the name as HTML code, it is showing up as a stri ...

Alter the style type of a Next.js element dynamically

I am currently working on dynamically changing the color of an element based on the result of a function //Sample function if ("123".includes("5")) { color = "boldOrange" } else { let color = "boldGreen" } Within my CSS, I have two clas ...

Transferring data to ng-model within ng-repeat loop

I am facing an issue with a form that is supposed to pass its inputs to ng-model before saving them into the database. One of the inputs is a dynamic value, specifically a pre-generated code retrieved from a database table. <div class="form-group" ng-r ...

JavaScript for loop similar to Python'sIn JavaScript, the

As someone who is new to programming, I primarily use Python but have now encountered a situation where I need to work with JavaScript for a project utilizing Phonegap. The query retrieved from the server looks like this: [["CompanyName", "lat", "long", ...

Utilizing the fetch method for sending cross-origin JSON data to an Express backend

When attempting to use Fetch to send JSON data from a form and receive a response from an Express server, I am encountering an issue where I only see an empty object in the console instead of the expected JSON response with the form values. You can find t ...

The function to focus on this.$refs[("p" + index)] element is not available

I need help transforming a div into an input box when clicked, allowing me to edit the post inside a loop. Here is the button found on the post: <a @click="setFocusEdit(index)" v-if="isAuthor(post)" href="#" >Edit Me</a> And here is the spec ...

Leveraging Arrays with AJAX Promises

I am currently working on making multiple AJAX calls using promises. I want to combine the two responses, analyze them collectively, and then generate a final response. Here is my current approach: var responseData = []; for (var i=0; i<letsSayTwo; i++ ...

Error occurred due to an unexpected end of JSON input following a pending promise

I am currently developing a data handler that requires downloading a file for parsing and processing within the handler. To handle this, I have implemented the file request within a promise and called it asynchronously from other methods. Including the h ...

Monitoring an Angular form for changes in its $dirty state can provide valuable insights into performance

I have a question about my Angular application. I am dynamically setting placeholders in my form based on the time of day using code inside the controller. Is there a way to clear all placeholders when a user starts typing into any field of the form? I h ...

Generating unique ID's for data posting in PHP and JavaScript

I've developed a dynamic form that includes an "add more" button to generate an XML file for data import purposes. Users can fill out the form and add as many entries as needed by clicking on the "add more" button. The inputted data is then processed ...

Designing a hybrid app navigation menu

In our development plans, we aim to design a cutting-edge hybrid mobile application by incorporating HTML, Kendo-UI, and AngularJS. One crucial component of the mobile app will be a left sidebar navigation menu featuring various items for navigating throu ...

Pass the selected ID from a Vue.js select component to an Axios post request and then render another select

Forgive me if this is a silly question, as I am new to Vue.js and JavaScript. I'm having trouble getting the id from one select element and using it in another API to display models in the next select element. The listings are working fine when I hard ...

AngularJS - Sending configuration values to a directive

I'm trying to figure out how to pass parameters (values and functions) to an Angular directive. It seems like there should be a way to do this in Angular, but I haven't been able to locate the necessary information. Perhaps I'm not using th ...