Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularJS element.on callback and scope.$apply

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 ?

like image 453
David V. Avatar asked Dec 12 '13 23:12

David V.


Video Answer


2 Answers

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

like image 112
F Lekschas Avatar answered Oct 31 '22 00:10

F Lekschas


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.

like image 38
shaunhusain Avatar answered Oct 30 '22 22:10

shaunhusain