Sam R.
Sam R.

Reputation: 16450

ui-router event.preventDefault won't render the ui-view

I'm trying to redirect to another state on stateChangeStart but event.preventDefault and $state.go() are not able to render the view. If I comment out both of them, it'll start working. Here is the plunker:

var example = angular.module("example", ['ui.router']);

example.config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state("root", {
            url: "/",
            abstract: true,
            template: '<ui-view>'
        })
        .state("root.second", {
            abstract: true,
            template: '<ui-view>',
        })
        .state("root.second.a", {
            url: "a",
            template: "second a template",
        })
        .state("root.first", {
            abstract: true,
            template: '<ui-view>'
        })
        .state("root.first.b", {
            url: "b",
            template: "first a template"
        });

    $urlRouterProvider.otherwise("/b");
});


example.run(function ($rootScope, $state) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        event.preventDefault();
        $state.go("root.second.a", {}, {notify: false});
    });

});

Upvotes: 0

Views: 167

Answers (1)

Anid Monsur
Anid Monsur

Reputation: 4538

Setting notify to false prevents the view directive from doing it's job. Instead of using notify: false, which I assume you're doing to avoid the $stateChangeStart function, you could conditionally call $state.go().

$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
  if (toState.name !== 'root.second.a') {
    event.preventDefault();
    $state.go('root.second.a');
  }
});

Plunker: http://plnkr.co/edit/tJPxXGir5YSSPG5jGodn?p=preview

Upvotes: 1

Related Questions