angularJS element.on 回调和 scope.$apply [英] angularJS element.on callback and scope.$apply

查看:26
本文介绍了angularJS element.on 回调和 scope.$apply的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个例子中,我有一个带有附加指令的输入.该指令旨在在输入旁边显示消息.还有另一个输入和一个按钮来添加消息.一旦显示了一些消息,关注带有附加指令的输入应该清除消息.http://jsfiddle.net/viro/WBqxf/

In this example, I have an input with an attached directive. The directive is meant to display messages next to the input. There's another input and a button to add messages. Once some messages are displayed, focusing on the input with the attached directive should clear the messages. http://jsfiddle.net/viro/WBqxf/

所以我有一个带有隔离模型的指令,并且我正在尝试在具有该指令的元素进入焦点时更新模型.似乎我必须在作用域中包装事件回调.如果我想更新模型,请使用 $apply:

So I have a directive with an isolated model, and I'm trying to update the model when the element which has the directive goes into focus. It seems like I have to wrap event callbacks in scope.$apply if I want to update the model:

element.on('focus',function(){
    scope.$apply(function(){
        console.log("focus !");
        scope.tstMsg=[];
    })
});

我想我必须将它包装在 $apply 中,因为我使用的是 jqlite 事件回调,我猜它们在 angularJS 的外部"运行,但我没有在文档中找到明确说明.

I suppose I have to wrap it in $apply because I'm using jqlite event callbacks and I guess they run "outside" angularJS, but I didn't find it clearly stated in the docs.

我做得对还是黑客?

有更好的方法吗?

推荐答案

scope.$apply 将导致 $digest 运行,因此作用域上的任何观察者将检查更改并在适当时触发.因为正如您所说,您只是绑定到一个事件(仅在适当的情况下进行 addEventListener/attachEvent)执行范围.$apply 在此上下文中是有效的.

scope.$apply will cause a $digest to be run so any watchers on the scope will check for changes and fire where appropriate. Since as you say you're just binding to an event (on just does addEventListener/attachEvent as appropriate) doing the scope.$apply in this context is valid.

这篇关于angularJS element.on 回调和 scope.$apply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆