Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UI- Router -- run function on every route change -- where does the state name live?

Using Angularjs and UI-Router, trying to run a function every time state changes

$rootScope.$on('$stateChangeStart',
        function(toState){
            if(toState !== 'login')
            UsersService.redirect();
        })

I put this in .run() and i can successfully log out toState every time route changes. However, i can't seem to find the property which has the name of the state that we are going to. If someone can tell me where to find that, i think i should be in good shape.

like image 668
user2827377 Avatar asked Jun 23 '14 01:06

user2827377


People also ask

How does a ui router work?

The UI Router is a routing framework that changes the views of the application based on not just the URL, but the state of the application as well. It helps in bridging the gap between the traditional frameworks, by allowing nested views, named views, passage of data between two different views, and so on.

How do we set a default route in route provider?

Creating a Default Route in AngularJS The below syntax just simply means to redirect to a different page if any of the existing routes don't match. otherwise ({ redirectTo: 'page' }); Let's use the same example above and add a default route to our $routeProvider service. function($routeProvider){ $routeProvider.

What does ui-sref do?

A ui-sref is a directive, and behaves similar to an html href . Instead of referencing a url like an href , it references a state. The ui-sref directive automatically builds a href attribute for you ( <a href=...> </a> ) based on your state's url.

What is ui-sref active in AngularJS?

ui-sref-active can live on the same element as ui-sref / ui-state , or it can be on a parent element. If a ui-sref-active is a parent to more than one ui-sref / ui-state , it will apply the CSS class when any of the links are active.


1 Answers

Ended up with this and it does what i want.

$rootScope.$on('$stateChangeStart',
        function(event, toState, toParams, fromState, fromParams){
            if(toState.name !== 'login' && !UsersService.getCurrentUser()) {
            event.preventDefault();
            $state.go('login');
            }
        });
like image 124
user2827377 Avatar answered Oct 18 '22 04:10

user2827377