thurmc thurmc - 5 months ago 18
Javascript Question

Call function after delay on page load using Angular

I am trying to call a function in Angular 2.5 seconds after a page loads to see if a form field has been autofilled. The function is being called but for some reason is only called if I navigate away from the field, change the tab, minimize the browser, etc. How can I accomplish this without requiring the user to do any of these actions (i.e. it is called 2.5 seconds after page load no matter what). I have two different implementations I have tried below but they behave the same way.

Method 1:

var timer=false;
$scope.$watch('email', function(){
if(timer){
$timeout.cancel(timer)
}
timer= $timeout(function(){
$scope.emailChanged();
}, 250)
});


Method 2:

<div class="form-managed" ng-init="load()"></div>

$scope.load = () => {
setTimeout(() => {
$scope.emailChanged();
}, 2500);
};


Update:

From comments I changed the code to use $timeout instead of my other implementations. I also verified that the function is being called in any of the implementations however the value of the field still shows as null when I try to extract it. Current code below.

$timeout(() => {
debugger;
var thisEmail = document.getElementById("buyerEmail");
$scope.emailChanged();
}, 5000);


Input field:

<input type="email" class="form-control input-lg" name="email" id="buyerEmail" placeholder="Email address" autocomplete="email" ng-model-options="{updateOn: 'blur'}" ng-change="emailChanged($event)" required />

Answer

It doesn't make a difference how long the delay is that you add. If you populated the value of your email input from code, Angular doesn't see the change. This is why you only see the change reflected once you resize or make some other change that forces Angular to process the page.

While you didn't show it, I assume you have some code somewhere to assign the email value. Something like this, perhaps:

$("txtEmail").val(myEmailVariable);

Change it to this:

$timeout(function () {
  $("txtEmail").val(myEmailVariable);
});
Comments