Ignoring the change event in an input field after the user cancels with a confirmation dialog is a common challenge faced when using AngularJS

I'm currently working on a directive that will display a confirmation message to the user whenever there is a change in the input field, specifically radio buttons.

For example, if the user selects "normal" and then switches to "tracked" but decides to cancel the confirmation box, I want both the model and view to revert back to "normal".

The code for my input field looks like this:

<form name="form1">
  <input type="radio" id="blah" name="blah" ng-model="emailType" value="normal" ng-confirm-click="Are you sure you want to do that?">
  <input type="radio" id="blah2" name="blah2" ng-model="emailType" value="tracked" ng-confirm-click="Really?">
</form>

I've tried using ng-change, but it doesn't work as expected because the confirmation prompt comes too late - after the value has already changed.

In my attempt to solve this issue, I came across a helpful post on Stack Overflow. Here is what my directive currently looks like:

This is how the directive is structured:

app.register.directive('ngConfirmClick', [ function () {

    return {
         priority: -1,
         restrict: 'A',
         require: 'ngModel',
         link: function (scope, element, attrs, modelCtrl) {
                   var message = attrs.ngConfirmClick;

    modelCtrl.$parsers.push(function (inputValue) {
                    var modelValue = modelCtrl.$modelValue;

                    if (inputValue !== modelValue && message && !confirm(message)) {
                        modelCtrl.$viewValue = modelValue;
                        modelCtrl.$render();
                    }

                    return modelCtrl.$viewValue;
                });
          }
    }
}]);

The parser triggers before the model changes, allowing me to confirm or cancel the action through the confirmation box. However, despite the logic in place, the model still gets updated with the new value after the function returns.

I also attempted to use $rollbackViewValue() based on another online resource, but encountered an error stating that the function was not defined.

It seems like I'm missing a crucial step somewhere. Can anyone provide some guidance on this matter?

Answer №1

Discovered the solution to your issue.

Replace

modelCtrl.$viewValue = modelValue;
with
modelCtrl.$setViewValue(modelValue);

Link to jsfiddle

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

Transferring previously obtained data to templateProvider within AngularJS

I'm currently working with AngularJS 1.3 and UI-Router. I have a state set up with a resolve and a templateProvider. My goal is to utilize the data fetched from the database in the resolve within the templateProvider without having to make duplicate ...

Creating an event handler in jQuery that responds to a specific pattern of clicks

There are numerous reason codes (e.g. RC1, RC2...) and I want to provide users with a text box for inputting comments related to each reason code. Additionally, users should have the option to add multiple text boxes for each reason code. To enable users ...

Converting a JavaScript function to asynchronous with callback functionality

In the past, I had implemented certain methods in MyClass: MyClass.prototype.method1 = function(data1) { return this.data111.push(data1); }; MyClass.prototype.method2 = function(i) { var data = this.method1(i); if (data.condition1 != null ...

Code snippet causing element block JavaScript malfunction

I'm attempting to create a basic automatic slideshow using JavaScript. let currentIndex = 0; startSlideshow(); function startSlideshow() { let slides = document.getElementsByClassName("slide"); for (let i = 0; i < slides.length; i++) { ...

Incorporate the user's input text into the paragraph

Is there a way to dynamically insert user input text into a pre-existing paragraph? For instance: Enter Your Name: Alice Would be transformed into <p>Hello, my name is Alice</p> I am looking for a solution that can work on the same HTML pag ...

Click on the marker to adjust the map's central position

I've successfully created a leaflet map featuring an array of 3 different locations, each marked with a popup window. Now, I'm looking to implement the functionality that will allow the center of the map to change dynamically when a user clicks o ...

Steps for showing the text entered into the input box as soon as it is typed:

I am attempting to create a feature where text is displayed as soon as it is typed into an input box. Currently, my JavaScript function is not working at all. I simply want the function to display text when it is typed into or erased in the text boxes. & ...

What are the steps for implementing custom edit components in material-react-table?

I am currently using the official material-react-table documentation to implement a CRUD table. You can find more information at this link: . However, I encountered an issue while trying to utilize my own custom modal components for the "create new" featur ...

Creating a dynamic grid within an application

I need help figuring out how to begin solving this issue. In my Rails application, I'd like to create a dynamic grid. Specifically, I want to input a row of data (such as from a table) into a single cell on the grid. After that, I would like to move t ...

Tips for Selenium: Automatically Clicking a Button on a Web Page with JavaScript

How can I use selenium to click a button that doesn't really act like a traditional 'button'? <a href="javascript:void(0)" id="ajax_more_button">さらに読み込む</a> Hello, I am attempting to extract URL ...

There is a delay in updating ng-if/ng-hide in real time on the HTML page

Assistance needed for implementing a slight adjustment in AngularJS with TypeScript. The requirement is to change the text of a button for 3 seconds upon clicking, then revert back to its original text. Two HTML elements are created for this purpose, each ...

Encountering difficulties when attempting to establish a POST request with $resource in AngularJS towards a REST API

I've been diving into the world of the MEAN stack, and successfully set up a REST API to post reviews to a MongoDB collection. Here's my service setup: angular.module('myApp') .constant('baseURL', 'http://localhost: ...

Error message in Node.js and Express: Attempting to modify HTTP headers after they have already been sent to the

element, I have thoroughly analyzed various responses on StackOverflow and GitHub Issues to address my issue, but unfortunately, none of them have provided a solution for my specific problem. Below is the code snippet (bear in mind that some parts may be ...

Updating an Angular directive with dynamically added ng-module and ng-change attributes

Can someone check if I'm on the right track? Preamble: I've created a Typeahead class that fetches data and keeps it within itself. The class has the following structure: input: stores the search text. list: stores the results. change: a funct ...

Improved explanation of DOM elements in raw JavaScript

Is there a more efficient way to dynamically create this DOM block: <tr> <td>text</td> <td><input type="checkbox"></td> </tr> I have a function that adds a nested tr element to my tbody: function inse ...

Error encountered: The Bootstrap modal() function is showing as undefined when using npm modules

Every time I attempt to call $("#myDiv").modal(), an error occurs. The error message reads: Uncaught TypeError: undefined is not a function This error has popped up in different scenarios, with various parameters being passed to modal(). Many solutions o ...

Having trouble with protractor's sendKeys function when trying to interact with md-contact-chips

Does anyone know how to set a value using sendKeys in Protractor for md-contact-chips? I attempted to use element(by.model('skills')).sendKeys('Java'); but it doesn't seem to be working. Any suggestions on how to approach this in ...

What is the correct method for retrieving values from a JSON array?

To extract information from a JSON file, I have created a function as shown below: function getarray(){ $http.get('http://localhost/prebuilt/countries.json') .success(function(data) { $scope.countries = data; }); return data; } Howe ...

Tips for connecting JavaScript to a specific onclick function script

I want my website visitors to interact with a button in order to trigger the opening of a modal that I have custom created using JavaScript. The process involved copying and pasting CSS, HTML, and JS into a single HTML document, which was then uploaded to ...

Choose carefully when to utilize forkJoin

In a particular scenario, I need an application to generate menus based on specific contexts. Here are the definitions for menuA and menuB: // menuA example from a given source menuA() { return [ { a: 'demo1', b: &apo ...