Sagar
Sagar

Reputation: 647

Not able to change path using $location service even after using $scope.apply

I am wondering why I am not able to change my view using location service even after I use -

$scope.$appy() or $scope.apply;

I did research before posting my question. I got results of similar questions and none of those are matching my scenario.

I do not want to use timer function for achieving the same like specified in link because its CPU intensive: angularjs path not changing even after apply

The strange behavior in my app is I am able to change location with following code in other scripts:

$location.path("authenticate").replace();
$scope.$apply();

OR

$location.path("authenticate").replace();
$scope.apply;

Which works fine without any issues.

The only difference is: Above code works fine when it gets executed without any event trigger but it takes to blank page if I use above code on button click event like this:

 <li data-ng-click="logout()"><a data-ng-href="#">Sign Out</a></li>

Any help will be helpful.

Upvotes: 0

Views: 71

Answers (2)

VadimB
VadimB

Reputation: 5711

If you are trying execute your code after some async execution (when logout happens, etc) - your Angular engine might not know on operation completion.

Use scope.apply with concrete action inside. Also be aware of digest process, this can fire exception

$scope.$apply(function(){
   if(!$scope.$$phase) {
       $location.path('authenticate');
   } 
});

Upvotes: 0

CraigR8806
CraigR8806

Reputation: 1584

Try encapsulating the call within the $scope.apply() like so:

$scope.$apply(function(){
    $location.path('authenticate');
});

Upvotes: 0

Related Questions