【问题标题】:Simple AngularJS and ui.router example not working简单的 AngularJS 和 ui.router 示例不起作用
【发布时间】:2015-09-01 15:49:33
【问题描述】:

我试图在一个非常简单的示例中使用ui.router,但无法弄清楚为什么它不起作用。

代码如下:

<!doctype html>
<html ng-app="test">
    <head>
        <meta charset="utf-8">
        <title> ngTest </title>
    </head>
    <body>

        <a ui-sref="pages.home">Home</a>
        <div ui-view></div>

        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>
        <script>
            var $app = angular.module('test', ['ui.router']);
            $app.config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider){
                $urlRouterProvider.otherwise('/');
                $stateProvider.state('pages', {
                    url: '/pages',
                    abstract: true
                });
                $stateProvider.state('pages.home', {
                    url: '/home',
                    template: '<h1> Hello </h1><p> {{ message }} </p>',
                    controller: function($scope){
                        $scope.message = 'Hey, It works !';
                    }
                });
            }]);
        </script>
    </body>
</html>

单击“主页”链接时,URL 会更改,但视图不显示!

提前感谢您的帮助:)

【问题讨论】:

  • 尝试将url: '/pages',更改为url: '#/pages',
  • ..和控制台布局iis?)
  • @Lal : 为什么需要#/pages?你能解释一下吗?
  • 尝试将带有 'ui-view' 指令的模板添加到父状态(页面)。
  • @Lai : 在 url 中添加“#”并不能解决问题

标签: angularjs angular-ui-router


【解决方案1】:

您需要稍微修改结构。如果您要使用类似的路线

$stateProvider.state('pages.home', {

那么您需要在该模板中专门指定 ui-view 以供渲染子级。所以应该是这样的:

$stateProvider.state('pages', {
    url: '/pages',
    abstract: true,
    template: '<div ui-view></div>' //pages.home template will be nested into this template.
});

$stateProvider.state('pages.home', {
    url: '/home',
    template: '<h1> Hello </h1><p> {{ message }} </p>',
    controller: function($scope){
        $scope.message = 'Hey, It works !';
    }
});     

试试看。干杯。

要了解更多信息,请访问:https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views

【讨论】:

  • 是的,模板丢失了,谢谢
  • @webNeat:是的,诀窍是,父模板需要包含另一个ui-view,它将嵌套子模板。干杯。
【解决方案2】:

只需将url 更改为templateURL。并确保您指定了 html 的确切位置。

干杯。

【讨论】:

  • 我在html标签中使用ng-app
  • 所以,尝试将您的 url 更改为 templateUrl .. 然后确保您指定了 html 的确切位置。
  • 模板没问题,问题是父状态下缺少模板
  • 啊,好吧,兄弟,你说得对。很高兴你解决它。
猜你喜欢
  • 1970-01-01
  • 2013-08-02
  • 2015-09-12
  • 1970-01-01
  • 2012-07-01
  • 2015-11-23
  • 2016-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多