angularJS element.on回调和范围。$ apply

时间:2021-03-23 15:06:14

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/

在这个例子中,我有一个附加指令的输入。该指令用于显示输入旁边的消息。还有另一个输入和一个添加消息的按钮。显示某些消息后,使用附加指令关注输入应清除消息。 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:

所以我有一个带有隔离模型的指令,并且我试图在具有指令的元素成为焦点时更新模型。好像我必须在事件范围内包装事件回调。$ apply如果我想更新模型:

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

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.

我想我必须将它包装在$ apply中,因为我正在使用jqlite事件回调,我猜它们在“外部”angularJS运行,但我没有在文档中明确说明。

Am I doing it right or is it a hack ?

我做得对吗还是黑客攻击?

Is there a better way to do it ?

有没有更好的方法呢?

2 个解决方案

#1


2  

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.

范围。$ apply将导致运行$摘要,因此范围内的任何观察者将检查更改并在适当的时候触发。因为正如你所说,你只是绑定到一个事件(在适当的时候只是addEventListener / attachEvent)来做范围。$ apply在这个上下文中是有效的。

#2


3  

Whenever you are using a thrid party library and perform changes you need to let Angular know by calling $apply().

每当您使用第三方库并执行更改时,您需要通过调用$ apply()来让Angular知道。

As @charlietfl mentioned ng-focus is even easier:

正如@charlietfl所说,ng-focus更容易:

Controler

$scope.focus = function() {
    // Do something
}

HTML

<input ng-model="inp" tst-msg="message" ng-focus="focus()" />

See jsFiddle

#1


2  

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.

范围。$ apply将导致运行$摘要,因此范围内的任何观察者将检查更改并在适当的时候触发。因为正如你所说,你只是绑定到一个事件(在适当的时候只是addEventListener / attachEvent)来做范围。$ apply在这个上下文中是有效的。

#2


3  

Whenever you are using a thrid party library and perform changes you need to let Angular know by calling $apply().

每当您使用第三方库并执行更改时,您需要通过调用$ apply()来让Angular知道。

As @charlietfl mentioned ng-focus is even easier:

正如@charlietfl所说,ng-focus更容易:

Controler

$scope.focus = function() {
    // Do something
}

HTML

<input ng-model="inp" tst-msg="message" ng-focus="focus()" />

See jsFiddle