Angularjs - How to undo a change event on a popup menu when the confirmation dialog is false?

I am using Angularjs. My problem is that when I select a new option from my drop-down list, a dialog box will appear. If the result of the dialog is false, the selected dropdown option should be the same. Ideas from other developers are analyzed. Thank you in advance!

Check out my code snippet below:

<div ng-app="myApp" ng-controller="myCtrl">
  <select ng-model="myDropDown" ng-change="Dialog()">
    <option>a</option>
    <option>b</option>
  </select>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.Dialog = function () {
        var dialog = confirm('Continue?');
        if(!dialog) {
    	    alert("Option must not change");
            /** The problem is the dropdown still select the option. **/
        }
    }
});
</script>
Run code
+4
source share
1 answer

Here is a trick you don't know:

ng-change="dialog(myDropDown)"         // pass the NEW value of myDropDown
ng-change="dialog('{{myDropDown}}')"   // pass the OLD value of myDropDown

When called up, dialog()you can pass the previously selected option as a parameter.

Then just rollback if the dialog is canceled.

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
    $scope.dialog = function(prev) {
        var dialog = confirm('Continue?');
        if(!dialog) {
            $scope.myDropDown = prev;
            alert("Option must not change");
        }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <select ng-model="myDropDown" ng-change="dialog('{{myDropDown}}')">
    <option>a</option>
    <option>b</option>
  </select>
</div>
Run code
+6

Source: https://habr.com/ru/post/1681242/


All Articles