【问题标题】:Cancel ng-change event [duplicate]取消 ng-change 事件 [重复]
【发布时间】:2016-05-30 11:26:05
【问题描述】:

有没有办法取消ng-change事件?

实际上我想在选择框中有一个选项,但不希望用户选择它,但想给出警告消息,然后选择上一个选项。

为此,我认为最好的方法应该是如果我可以以某种方式取消 ng-change 事件,这样它就不会产生任何影响,类似于我们在 html onchange 事件中返回 false 时它不会让你更改选项。

我还尝试以某种方式存储以前的值,然后在ng-change 事件中设置该值,但后来发现ng-change 没有传递event 变量,因此我找不到触发事件的元素。

有什么想法吗?

编辑

像这样的

<select ng-change="DeliveryMethodChange(item)" ng-model="item.DeliveryMethodId" ng-options="method.Key as method.Value for method in deliveryMethods">
         <option value="">(Please Select)</option>
</select>

脚本

$scope.DeliveryMethodChange = function(item) {

    if (item.DeliveryMethodId.toUpperCase() == 'SH') {
          // here I want to reset the value to the previously selected value
          alert('You cannot select this delivery method');
          return false;
    }

    // rest of the code

};

【问题讨论】:

  • 你能分享一些你的代码让我帮忙吗?
  • 其实我的问题不是代码特定的,一般我想以某种方式取消ng-change事件
  • 你为什么不在事件处理程序中设置一些逻辑呢?它真的看起来像一个 XY 问题。您最好提供一些简单的示例来复制您的问题并清楚地解释您的预期行为
  • 我做到了,但我没有找到将值重置为旧值的方法。为此,我需要在 ng-change 中引用 select 以及最后选择的值。
  • 尝试在模型上使用手表。在那里你有新的和旧的价值。

标签: javascript jquery angularjs


【解决方案1】:

已经很晚了,但这个答案回答了这个问题。 本质上,您可以 {{value}} 引用当前值,因此将其作为参数传递给您的更改函数,如果您不喜欢您所做的,则恢复该字段。

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

【讨论】:

    【解决方案2】:

    这可能是答案;

    $scope.DeliveryMethodChange = function(item) {
    
         $scope.$watch('DeliveryMethodId', function (newVal, oldVal) {
                        if (newVal == 'SH') {
                            item.DeliveryMethodId = oldVal;
                        }
                    });
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 2018-10-11
      • 1970-01-01
      相关资源
      最近更新 更多