leo c leo c - 10 months ago 65
AngularJS Question

Why is $location.path not working until I click on the screen

I have the following code that aims to redirect to the './mainlandingpage' after a successful authentication. Here is the code from the controller:

cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
// pass token to use for getting credentials later
sessionStorage.Token = result.getIdToken().getJwtToken();
$scope.messageText = globalData.LoggingIn;
console.log(' after location');


onFailure: function(err) {

The console from Firebug shows the following:

POST https://cognito-idp.ap-northeast-1.amazonaws.com/200 OK 704ms
POST https://cognito-idp.ap-northeast-1.amazonaws.com/200 OK 401ms
after location

So, I know that the code went through the $location.path line but my problem is nothing happens to the page until I click something on the page (doesn't need to be a button). Is this normal behavior?

Answer Source

You are modifying $location path from outside Angular world(i.e. custom event authenticateUser's onSuccess event). That's why the changes aren't being reflecting in instantly in the URL.

Changing angular bindings from outside world doesn't update current changes directly on the page unless it runs through digest cycle. To make those changes happen, you have to call digest cycle manually to tell Angular digest system that some changes have been happened in application context. Since you have to kick off digest cycle to make them in sync. For kick off digest cycle you could use $timeout(most preferred)/$scope.$apply function.

//inject `$timeout` in controller function