【问题标题】:Using ng-model-options updateOn:blur with uib-datepicker popup使用 ng-model-options updateOn:blur 和 uib-datepicker 弹出窗口
【发布时间】:2016-11-21 05:43:00
【问题描述】:

我有一个输入,允许用户通过 uib-datepicker 日历 (https://angular-ui.github.io/bootstrap/) 键入或选择日期。当用户点击输入时,日期选择器弹出允许用户进行选择这是输入:

<input
     datepicker-append-to-body="calendarCtrl.appendToBody"
     uib-datepicker-popup="calendarCtrl.dateFormat"
     ng-model="calendarCtrl.ngModel"
     ng-click="calendarCtrl.open"/>

我需要允许用户选择在用户模糊输入之前不更新 ng-model。为此,我正在尝试使用 ng-model-options。

 ng-model-options={updateOn: 'blur'}

当用户在输入中键入日期时,这非常有用 - ngModel 在发生模糊之前不会更新,并且在模糊之前不会运行任何验证。问题在于它破坏了日历弹出窗口的功能,因为当用户然后单击打开的日历以选择日期时没有任何反应。我假设是因为当用户点击日历时,输入端会发生模糊事件??

有人遇到过这个问题吗? datepicker 中是否有 ng-model-options 选项或其他内容,允许用户仍然从 datepicker 中进行选择,但在输入出现模糊之前不更新 ng-model?

谢谢

【问题讨论】:

    标签: javascript angularjs twitter-bootstrap datepicker angular-ui-bootstrap


    【解决方案1】:

    听起来您可以在日期选择器中为 ngModel 使用临时属性 ng-model="calendarCtrl.tempSelectedDate"

    然后使用 ngBlur 事件 (https://docs.angularjs.org/api/ng/directive/ngBlur) 更新真实属性,即。设置calendarCtrl.ngModel = calendarCtrl.tempSelectedDate

    此外,虽然没有什么能阻止您在 ngModel 中使用范围属性 calendarCtrl.ngModel,但如果您使用更有意义的名称(例如 ng-model="calendarCtrl.dateSelected"),则代码将更易于阅读。

    这是一个工作演示 http://plnkr.co/edit/90mDPqzadjPt09Tp4SlI?p=preview

    我对其他人的 datepicker plnkr 进行了分叉和扩展,并进行了两项更改:将 ng-blur="blurDate = startDate" 添加到 &lt;input&gt; 并使用 Blur Date: {{ blurDate }} 显示值。

    【讨论】:

    • 我添加了一个示例 plnkr
    • 在我的情况下,每次单击输入时都会调用 ng-blur,因为弹出的日历正在调用模糊。在我的模糊函数中,我将 ngModelController 设置为 $dirty,然后触发对任何错误的验证。我最终通过侦听输入元素上的 keydown 并将输入设置回 $pristine 来解决它。然后,当用户单击日历弹出窗口或通过单击离开来模糊输入时,表单将设置回 $dirty 并查找验证错误。哈克解决方案,但基于预先存在的代码似乎是唯一的选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 2020-08-10
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多