【问题标题】:Custom ng-model Directive not firing digest自定义 ng-model 指令不触发摘要
【发布时间】:2013-08-17 13:35:12
【问题描述】:
我创建了一个自定义指令,允许以各种格式输入日期,但是当您完成输入日期并留下输入时,不会触发摘要。
如何让摘要触发?
详情
该指令很高兴地允许用户输入文本并以标准日期格式返回一个字符串,以便模型在其有效日期时使用。
它使用格式化程序和解析器来执行此操作,并且实际处理是在输入标签的 on blur 事件中完成的。
Plunkr 显示了格式化日期的指令,如果您随后更改输入框中的日期,您会看到它旁边的绑定值永远不会更新。
此时我只需要它触发摘要/更新模型
【问题讨论】:
标签:
angularjs
angularjs-directive
【解决方案1】:
您只需要在bind 期间添加一个$apply。每当您绑定到 DOM 事件时,都需要 $apply 强制进行摘要。
// configure events on the element
function configureEvents(element, scope, ctrl, allowNull) {
// remove handlers that would fire events while the user
// is inputting data
element.unbind('input').unbind('keydown').unbind('change');
// bind to the blur event as we know the user should have
// finished inputting when they leave the control
element.bind('blur',function() {
scope.$apply(function() {
processUserInput(element, ctrl, allowNull);
});
});
}
为了实现这一点,我将作用域传递给configureEvents:
configureEvents(element, scope, ctrl, allowNull);
这是一个正在工作的fork of your Plunker。