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

"I have successfully removed the URL from index.html. However, I am now wondering how I can include them in app

I have modified the URL in index.html to remove query parameters, but now I need my app.component.ts file to still be able to access and work with those query params using ActivatedRoute. However, when I implemented the script in index.html to remove query ...

Troubleshooting the issue of Angular 2 error: Cannot access the 'getOptional' property

Currently, I am navigating my way through angular 2 and attempting to define a service named searchservice. I want to inject this service in the bootstap part of my project: import {SearchService} from 'src/service'; Here is the code for the Se ...

How can we modify this function to interpret multiple selections at once?

For the task of displaying multiple selections from a scrolling list to an alert, I have implemented the following function: var toppings = ""; function displaySelectedToppings() { var topList = document.getElementById('to ...

The virtual method 'android.location.Location' was called in error

I'm using WL.Device.Geo.acquirePosition(onGeoLocationSuccess, onGeoLocationFailure, options) from MobileFirst to retrieve a device's location. Initially, everything works smoothly as I successfully obtain the location. However, after clearing t ...

Creating a video that plays frame-by-frame on an HTML5 canvas and can be controlled with a slider

I am currently working on a walkthrough video where the user has the ability to slide a UI slider across the screen, causing the camera to navigate through a 3D space. The video itself has been exported in jpg frames, numbered from 0 to 350.jpg. My appro ...

Utilize images stored locally in ReactJS

My path to the image is: ../src/assets/images/img_name.jpg" And my path to the file.js is: src/file_name.js If I include the following code in file.js: Import img_name from "../src/assets/images/img_name.jpg" Then reference the image pa ...

Guide to parsing JSONP information using Express

I am attempting to transfer data from phonegap to an express application. Below is the code I am using: Phonegap: $.ajax({ type: 'POST', url:"http://127.0.0.1:3000/test", data: {"test":"this works!"}, dataTyp ...

Comparison between Mobile Phone's innerWidth and innerHeight Versus Resolution

My test phone, the Galaxy S3 Mini, has a resolution of 800x480 according to its specs. Strangely, when I run the following code in my HTML game: window.innerWidth window.innerHeight The width appears as 533 and the height as 295. I recently discovered ...

When sending an ajax request with HTML data as the payload

While working on an MVC program, I encountered an issue when trying to send data from a TextArea to the controller upon a button click. Everything worked fine until I had HTML-based data inside the TextArea. Here's a snippet of the HTML code: <te ...

When I refresh the page in Angular2, the router parameters do not get loaded again

When loading my application on routers without parameters, everything is normal. However, when trying to use a router with params, the application fails to load. For example: localhost:3000/usersid/:id The code for the router is as follows: const appRou ...

Is it possible to maintain the component's DOM state when navigating away and then returning in Angular?

After spending several days researching this issue, I find myself at a dead end. I thought I was dealing with a common scenario: A user navigates to a specific page, makes some changes (such as editing an input field, scrolling through grid data, or chang ...

What is the best way to search for items using only a portion of a phone number or typing a name in any case (uppercase, lowercase) and still get accurate results?

let contacts = [ { name: 'John', phone: 987654 }, { name: 'Sara', phone: 654321 } ] I am developing a contact manager app with various functions to manage contacts. Add new contac ...

Inconsistency in handling express routes results in empty req.body in certain routes

I have two different paths to follow. Before each request, a method needs to be executed: app.all('*',function(req,res,next){ console.dir(req.body); // Additional operations }); When I send a POST request to my first path: $http.post ...

Encountered an Angular SSR error stating "ReferenceError: Swiper is not defined"

When attempting to implement SSR (Server-Side Rendering) in a new project, everything runs smoothly and without issue. However, encountering an error arises when trying to integrate SSR into an existing project. https://i.sstatic.net/QOI6A.png ...

Creating a JSON File with an Illustrator Script

Currently, I've been working diligently on developing a system that allows me to export my swatches from Illustrator as a JSON object. This will greatly simplify the process of updating my App. By utilizing the illustrator scripting API, I've suc ...

Can two different versions of ReactJS run simultaneously on a single page?

Hey everyone, I'm curious if it's possible to have two different versions of ReactJS running on the same page, similar to how jQuery has jQuery.noConflict(). After doing some research, I came across some interesting findings: Two Reacts Won’t B ...

Having difficulty transforming the JSON data into the necessary format for Google Charts using JavaScript

The JSON data returned by the following controller is structured as shown below: [ {"classification":"CON","count":2}, {"classification":"PUB","count":1}, {"classification":"SENS","count":1} ] However, Google Charts requires the data to be in the followi ...

What is the best way to use CSS in ReactJS to insert an image into a specific area or shape?

Currently, I'm working on developing a team picker tool specifically for Overwatch. The layout consists of cards arranged horizontally on a website, all appearing as blank gray placeholders. These cards are positioned using the JSX code snippet shown ...

Authentication for file uploads in Angular 2 using Dropzone and passportjs

I am currently working on implementing authentication for an admin user using Express, Passport, and MySQL in a specific page. The authentication process works fine, but I am facing an issue with verifying whether the user is logged in while uploading file ...

What is the best way to ensure a cron job executing a Node.js script can access variables stored in an .env file?

Currently, I have a scheduled job using cron that runs a Node.js script. This script utilizes the dotenv package to access API keys stored in a .env file. Running the Node.js script from the command line retrieves the variables from the .env file successf ...