I have seen it mentioned it in AngularJS books. In AngularJS directives
Alex Vanston writes that it is a good practice to use setTimeout trickery
(at least in directives) without a full explanation for why? Just a good
practice... Hmm, I am puzzled here. I was under impression that javascript
in the browser runs in a single thread. But maybe I am wrong?
This is not the first time I have experineced this problem.
So I have a directive with an isolated scope where I assign a two-way
binding to the parent scope model and function binding to the parent
controller method.
It looks like this:
scope: {
model: '=',
switched: '&'
},
template: '<div class="switch" ng-click="toggle()"></div>',
link: function(scope, elem, attrs) {
scope.toggle = function() {
if (!scope.disabled) {
scope.model = !scope.model;
//setTimeout(function() {
scope.switched();
//});
}
};
}
So when I click on my directive element the toggle method is called and
there the scope.model, which is referencing the parent
scope.some.some.model is modified. Then I call the method on the parent
scope.
Everything works as intended with method calls. I can see that the
scope.model is properly modified but when I step into my parent switched
method the scope.some.some.model is still has the old value.
If I wrap the call to switched in a timeout and put a breakpoint in my
parent switched method the scope.some.some.model is properly updated. So
directive's scope.model is a reference to the parent scope.some.some.model
and supposed to change it right away before the call to the switched is
made, but alas: this is not the case. So what is the reasonable explanation
for this behavior? Why some books recommend using setTimeout?
Thanks for your help guys!!!
--
You received this message because you are subscribed to the Google Groups
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.