angularJS element.on回调和范围。$申请 [英] angularJS element.on callback and scope.$apply

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

问题描述

在这个例子中,我有一个附加的指令输入。该指令是为了显示旁边的输入消息。还有一个输入和一个按钮来添加消息。
一旦一些消息显示,专注于与连接的指令输入要清除的消息。
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/

所以我有一个孤立的模式指令,而我想,当有指令元素进入重点更新模型。
好像我必须包装事件回调的范围,如果我要更新模型$适用于:

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=[];
    })
});

我想我必须把它包起来在$适用,因为我使用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.

我这样做是正确的或者是一个黑客?

Am I doing it right or is it a hack ?

有没有更好的办法做到这一点?

Is there a better way to do it ?

推荐答案

范围。$应用将导致$文摘要运行等范围的任何观察家应该检查和消防在适当情况下。因为就像你说你只是绑定到一个事件(上少了点的addEventListener / attachEvent将酌情而定)做的范围。$应用在这方面是有效的。

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回调和范围。$申请的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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