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?