Angularjs - How to cancel change event on dropdown when the confirm dialog is false? [duplicate]

旧时模样 提交于 2019-11-27 06:15:32

问题


This question already has an answer here:

  • ng-change get new value and original value 6 answers

I am using Angularjs. My problem is when I select a new option in my dropdown, a dialog will appear. If the result of the dialog is false, the selected dropdown option must be the same. Getting ideas from other devs will be analyzed. Thank you in advance!

Refer to 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>

回答1:


Here is a trick you may not know:

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

When calling dialog(), you can pass as a param the previous selected option.

Then, just rollback it if the dialog is cancelled.

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>


来源:https://stackoverflow.com/questions/45051160/angularjs-how-to-cancel-change-event-on-dropdown-when-the-confirm-dialog-is-fa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!