ui-router event.preventDefault不会呈现ui-view

时间:2015-09-15 23:31:16

标签: javascript angularjs angular-ui-router

我尝试重定向到stateChangeStart上的其他州,但event.preventDefault$state.go()无法呈现视图。如果我将它们都注释掉,它就会开始工作。这是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});
    });

});

1 个答案:

答案 0 :(得分:1)

notify设为false prevents the view directive from doing it's job。我可以有条件地调用notify: false,而不是使用$stateChangeStart,我假设你正在做以避免使用$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