一尘不染

AngularJS-当确认对话框为假时如何取消下拉菜单中的更改事件?

angularjs

我正在使用Angularjs。我的问题是,当我在下拉菜单中选择一个新选项时,将出现一个对话框。如果对话框的结果为false,则所选的下拉选项必须相同。将分析其他开发者的想法。先感谢您!

请参阅下面的代码片段:

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

阅读 246

收藏
2020-07-04

共1个答案

一尘不染

这是您可能不知道的窍门:

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

调用时dialog(),可以将先前选择的选项作为参数传递。

然后,如果取消对话框,只需回滚即可。

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>
2020-07-04