【问题标题】:AngularJS prevent ngModel syncAngularJS 阻止 ngModel 同步
【发布时间】:2014-07-01 20:26:00
【问题描述】:

我有一个名为po-datepicker 的简单指令,它在屏幕上显示一个日期选择器,但允许用户手动输入日期:

<input type="text" ng-model="model" po-datepicker required />

这是指令:

myApp.directive('poDatepicker', function () {
    return {
        require: ['?^ngModel'],
        restrict: 'A',
        link: function ($scope, elem, attrs, ctrl) {
            var ngModel = ctrl[0];
            var picker = elem.datepicker();

            picker.on('changeDate', function(e) {
                ngModel.$setViewValue(e.date);
                ...
            });

            elem.parent().find('button').on('click', function() {
                picker.datepicker('show');
            });

            var changeFn = function(e) {
                // Here I have some logic that calls $setViewValue();
            };

            picker.on('hide', changeFn);
            elem.on('keyup blur', changeFn);
        }
    };
});

这按预期工作,但是当我尝试在输入中键入一个值时,它会更新 ngModel,更改范围中的变量,如何防止 ngModel 在输入中被更改?

Here is a plunkr,试试手动写一个值,你就会明白我在说什么了。

【问题讨论】:

  • 为什么不将文本输入与不同的模型对象相关联。然后在适当的时候,你可以将值提交给真实的模型对象。
  • 如果我这样做,required 之类的验证将不起作用,因为它需要 ngModel 进行验证

标签: angularjs angularjs-directive


【解决方案1】:

其实,经过一番研究,我找到了解决这个问题的办法。

我在论坛和问题上发现我需要取消绑定元素的事件,如下所示:

elem.unbind('input').unbind('keydown').unbind('change');

但该解决方案没有按预期工作。

问题是我目前使用的是Angular 1.2.x,我发现你还需要为指令设置一些优先级,例如:

return {
    require: ['?^ngModel'],
    priority: 1,
    ...
}

在这种情况下需要priority: 1,因为某些内部 Angular.js 指令的优先级。

Here is an updated plunker 设置了正确的优先级。

【讨论】:

    【解决方案2】:

    只需将“禁用”添加到输入 http://plnkr.co/edit/xFeAmSCtKdNSQR1zbAsd?p=preview

     <input type="text" class="form-control" ng-model="test" po-datepicker required feedback disabled/>
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 2021-11-29
    • 2012-08-12
    • 1970-01-01
    相关资源
    最近更新 更多