javascript - Angularjs focus unexpectedly requires an async setTimeout to work -
ok stackoverflow, riddle me this.
i have button click on toggles visibility of input. in scope function changes visibility use javascript set focus on input tag. want know why not work unless wrap in settimeout?
$scope.toggle = function() {   if ($scope.hideinput) {     settimout(function(){       input.focus();     }, 0);  // that's right, zero!   }   $scope.hideinput = !scope.hideinput; }; here's working jsfiddle button correctly sets focus , button doesn't:
can tell reason why.
first can't focus element, css display:none.
so in 1 (broken) method, focus element before displayed. because angular go line line , $scope.hideinput = !scope.hideinput; trigger watcher digest-loop. in loop input set display: block.
the timeout move focus command it's own thread, , $scope.hideinput = !scope.hideinput; trigger digest, too.  digest curiously fast enought display element before input.focus(); executed. 
this explanation understanding this, did me in curious problems of angular's timing.
maybe use ? http://ngmodules.org/modules/ng-focus-on
a directive set focus variable.
Comments
Post a Comment