1

Using angular ui-router I'm trying to make nested routing based on condition.i.e Want to check a condition before loading a state.

    .state('main.home', {
        url: "/:cnt",
        abstract: true,
        templateUrl: function ($stateParams) {
            return template1;
        },
        controller: "myController",
        resolve: {
            //Some model
            }],

            lazy: ['$ocLazyLoad', '$stateParams', function ($ocLazyLoad, $stateParams) {
               //lazily loaded controllers
            }]
        },
        onEnter: updateAppValues,
    }).state('main.home.default', {
        url: '',
        templateUrl: function ($stateParams) {
            return template2;
        },
        resolve: {
            lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
                //lazily loaded controllers
            }]
        },
        controller: 'myDefaultController',
    })

basically the nested router main.home.default must be loaded conditionally

if(something){
    //loaded state main.home.default
}

How can I achieve this?

2
  • you can write a if condition in resolve and in negative case use $location path to redirect to other route Commented Jan 24, 2017 at 8:49
  • 1
    Did you check if my answer solved your issue? :) Commented Jan 26, 2017 at 8:10

3 Answers 3

1

You can catch the event of route changing with:

$rootScope.$on("$routeChangeStart", function(event, next, current) {
    if(next.$$route == 'routeYouWantToAvoid') { // Or whatever you want
        $state.transitTo('main.home.default');
    }
});
  • next is the route you are going to.

  • current the route you are coming from.

Here is the documentation if you need more information.

Sign up to request clarification or add additional context in comments.

Comments

1

You can add if condition in the resolve of main.home.default. ex:

 resolve:{
    "check":function($location){   
        if('Your Condition'){ 
            //Do something
        }else{
            $location.path('/');    //redirect user to home.
            alert("You dont belong here");
        }
    }
}

Comments

0
app.run(function($rootScope, $state) {
   $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) { 
     if (toState.name == 'login'){ //if the name of that state is login
    //go to login page
      }
   });
});

Does this give you any idea? or

app.run(function($rootScope, $state){
   $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {
      if(*your condition*) {
         $state.transitTo('stateYouWantToGo')
         event.preventDefault()
       }
    });
 });

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.