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 ?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With