6

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

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 ?

4

2 回答 2

3

每当您使用第三方库并执行更改时,您都需要通过调用$apply().

正如@charlietfl 提到的 ng-focus 更容易:

控制器

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

HTML

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

jsFiddle

于 2013-12-13T01:28:57.660 回答
2

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

于 2013-12-12T23:51:46.110 回答