3

guys I am working on an angular js app which uses ui-router for deep linking and routing. I want to set up a variable on the $rootScope every time a state is visited/changed. I am able to accomplish that on subsequent state transitions via listening to $stateChangeSuccess but since the app is deep linked, I want to set the same variable when a state is directly hit from the address bar.

When I hit a specific URL from address bar e.g. Home/Summary/Change, $stateChangeSuccess doesn't fire hence I am not able to set the value.

Any suggestions on how I can listen to EACH state visit on my $rootScope.

3 Answers 3

1

You may use combination of $locationChangeStart and $route.current:

$rootScope.$on('$locationChangeStart', function (event, next, current) {
  if(!$route.current) {
    $rootScope.myVar = ...
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

still not able to receive $locationChangeStart event when i access #/Home/Summary/Change directly
0

I found a work around for this. I was not able to get $stateChangeSuccess on the first visit to a page so on initialization i called the function explicitly.

example code

var handle = function(){
//do something ...
}

$scope.$on('$stateChangeSuccess', handle); // call handle on each state change
handle(); // will only be called on initialization

might not be the cleanest way but it works

Comments

0

In the meantime they have implemented a $urlRouterProvider where you can add a when:

app.config(function($urlRouterProvider){
    // when there is an empty route, redirect to /index   
    $urlRouterProvider.when('', '/index');

    // You can also use regex for the match parameter
    $urlRouterProvider.when(/aspx/i, '/index');
})

So if you like to have Home/Summary/Change matching a state, you would write something like $urlRouterProvider.when('Home/Summary/Change','myhomestate') then the $stateChangeSuccess should fire correct. For more details about that provider look at https://github.com/angular-ui/ui-router/wiki/URL-Routing#urlrouterprovider

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.