angularJS element.on callback and scope.$apply

David V. picture David V. · Dec 13, 2013 · Viewed 8.2k times · Source

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 ?

Answer

F Lekschas picture F Lekschas · Dec 13, 2013

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

As @charlietfl mentioned ng-focus is even easier:

Controler

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

HTML

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

See jsFiddle