【问题标题】:Angular ui-router: adding templateUrl breaking routingAngular ui-router:添加 templateUrl 中断路由
【发布时间】:2015-12-16 20:00:51
【问题描述】:

我遇到的问题是,一旦将 templateUrl 添加到 ui-router 子状态,应用程序将不再执行到该状态的路由。当它只是一个模板时它工作得很好。

app.js

app.config(['$stateProvider', '$locationProvider', '$urlMatcherFactoryProvider', '$urlRouterProvider',
    function ($stateProvider, $locationProvider, $urlMatcherFactoryProvider, $urlRouterProvider) {

        $urlMatcherFactoryProvider.caseInsensitive(true);
        $urlMatcherFactoryProvider.strictMode(false);

        $urlRouterProvider.otherwise('/page-not-found');

        $stateProvider
                .state('dashboard', {
                    url: '/',
                    views: {
                        'header': {
                            template: 'header'
                        },
                        'nav': {
                            template: 'nav'
                        },
                        main: {
                            template: 'You are on the homepage'
                        }
                    }
                });

        $locationProvider.html5Mode(true);
    }]);

app.run(['$rootScope', 'userService', '$state', function ($rootScope, user, $state) {

    $rootScope.$on("$stateChangeError", console.log.bind(console));

    if (!user.exists) {
        $state.go('user.reg');
    }
}]);

User.states.js

.config(['$stateProvider', function ($stateProvider) {

    $stateProvider
            .state('user', {
                url: '/users',
                abstract: true,
                views: {
                    'header': {},
                    'nav': {},
                    'main': {
                        template: '<ui-view/>'
                    }
                }
            })
            .state('user.reg', {
                url: '/register',
                //template: 'This will show fine',
                templateUrl: '/app/Users/User.login.html' // this will break
            });

}]);

更新

如果我在初始页面中添加 ui-sref="user.reg",我可以使用 templateUrltemplate 导航到状态/页面。因此,当我尝试使用 state.go('user.reg');

时,这只是一个问题

这意味着解决方法是使用$location 提供程序来更改路径。具有相同的效果,但似乎相当错误

【问题讨论】:

  • 当它中断时,您会看到控制台错误吗?模板url路径是404吗?
  • @Starscream1984 完全没有错误,文件存在并且没有 404。它甚至没有路由到 user.register 状态,只是停留在索引状态
  • 我在您的示例和我的工作示例之间看到的唯一区别是,在我的代码中,url 字符串中没有前导斜杠...
  • @Starscream1984 删除后我得到了同样的效果。你使用的是什么版本的 angular/ui-router?
  • 角度 - v1.4.7 ui-router - v0.2.15

标签: javascript angularjs angular-ui-router


【解决方案1】:

问题在于您的相对路径。

看看这段代码:

$locationProvider.html5Mode(true);

你已经启用了 html5 模式,为了让它工作,你在你的 html 中设置了你的基本引用,它可能看起来像这样:

<base href="/">

您的问题可能是模板的路由不是“yoursite.com/app/Users/User.login.html”。

See this Plunker 获取代码的工作版本。然后进入 html 代码并取消注释掉 base 标记,注意它会中断。

【讨论】:

  • 模板在正确的位置,所以这不是问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
  • 2016-07-13
  • 1970-01-01
  • 2016-05-25
  • 2015-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多