【问题标题】:Angularjs - How to cancel change event on dropdown when the confirm dialog is false? [duplicate]Angularjs - 当确认对话框为假时,如何取消下拉更改事件? [复制]
【发布时间】:2017-12-16 11:55:24
【问题描述】:

我正在使用 Angularjs。我的问题是当我在下拉列表中选择一个新选项时,会出现一个对话框。如果对话框的结果为 false,则选择的下拉选项必须相同。将分析从其他开发人员那里获得的想法。提前谢谢!

参考下面我的代码sn-p:

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

【问题讨论】:

    标签: javascript angularjs dialog html-select


    【解决方案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>

    【讨论】:

    • 好招!谢谢你!
    • 我认为这个技巧只适用于 AngularJS,因为我用 AngularIO 尝试了这个 sn-p 并得到了错误:Uncaught Error: Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected
    猜你喜欢
    • 1970-01-01
    • 2016-10-09
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多