AngularJS element.on callback and scope. $ apply

In this example, I have an input with the attached directive. The directive is designed to display messages near the entrance. There is another input and a button for adding messages. After displaying some messages, 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 an element that has a directive goes into focus. It seems that I should wrap event callbacks in a scope. $ Apply if I want to update the model:

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

I suppose I need to wrap it in $ apply, because I use jqlite eventbackback, and I assume that they trigger angularJS “out”, but I did not find it clearly stated in the docs.

Am I doing it right or is it hacking?

Is there a better way to do this?

+6
source share
2 answers

scope. $ apply will trigger $ digest, so any observers in the area will check for changes and, if necessary, fire. Because, as you say, you are simply attaching to the event (it just adds addEventListener / attachEvent) that performs the scope. $ Apply in this context is valid.

+2
source

Whenever you use the thrid party library and make changes, you need to tell Angular by calling $apply() .

Since @charlietfl mentions ng-focus, this is even simpler:

Controler

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

HTML

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

See jsFiddle

+3
source

All Articles