【问题标题】:How to use ui-sref in ui-router AngularJS如何在 ui-router AngularJS 中使用 ui-sref
【发布时间】:2019-03-22 20:22:29
【问题描述】:

我有文件 index.html:

<!DOCTYPE html>
<html>
<head>
    <style>
        .navbar { border-radius:0; }
    </style>
    <link rel="stylesheet" type="text/css" href="lib/css/bootstrap.min.css">
    <script src="./node_modules/angular/angular.js"></script>
    <script src="./node_modules/angular-ui-bootstrap/dist/ui-bootstrap-tpls.js"></script>
    <script src="./node_modules/angular-ui-router/release/angular-ui-router.js"></script>
    <script src="lib/js/app.js"></script>
</head>

<body ng-app="nav-module">
    <a ui-view="home" ui-sref="home" ui-sref-active="active">home</a>
    <a ui-view="about" ui-sref="about" ui-sref-active="active">about</a>
        <ui-view>
        </ui-view>

</body>
</html>

和文件 app.js:

var app = angular.module("nav-module", ["ui.router",'ui.bootstrap']);
app.component('navComponent',{
    templateUrl: './navbar.component.html'
});
app.config(['$stateProvider',
'$urlRouterProvider',function($stateProvider,$urlRouterProvider) {
    $stateProvider
    .state('/home',{
        name: 'home page',
        url:'/home',
        template: '<h3>hello world!</h3>'
    })
    .state('/about',{
        url:'/about',
        component: 'navComponent'
    });
    $urlRouterProvider.otherwise('/home');
}]);

和导航栏.component.html:

<h1>nav bar</h1>

但是我无法点击标签来运行页面,当我在 URL 中更改 /about 时,控制台显示错误:

加载模板失败:./navbar.component.html

我不知道为什么。

【问题讨论】:

    标签: javascript angularjs angular-ui-router angularjs-components


    【解决方案1】:

    当您提到您的 templateUrl:'./navbar.component.html' 但你的文件名是 nav-bar.component.html。

    1. 首先删除 templateUrl 并在组件中使用 template:&lt;h1&gt;nav bar&lt;/h1&gt; 检查它。
    2. 如果没问题,那么您的错误是因为缺少模板网址引用或文件名。
    3. 然后使用 ../app/navtemplateurl.html 修复此问题,文件名为 navtemplateurl.html,位于 app 文件夹内。

    在你的模块中加入'ui.bootstrap.tpls'也可以解决这个问题

    更新:将 angularui 路由器引用从索引文件更改为 &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.0-rc.1/angular-ui-router.js"&gt;&lt;/script&gt;,因为 v0.4.2 或更早版本不支持 ui-router 中的组件模板。 您还需要对此进行更新。

    【讨论】:

    • 是的,同样的问题
    • 我删除了状态上的“/”,并且 ui-route 正在工作。但也不能解决加载模板问题
    • 现在可以了吗?我在本地机器上运行,完全没问题
    • 我想我和那个链接有同样的问题:stackoverflow.com/questions/16251420/…。但是当我在服务器上运行它时,它显示了同样的问题
    • 尝试在索引文件头部的顶部使用
    猜你喜欢
    • 2014-08-22
    • 2015-01-02
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 2014-10-28
    相关资源
    最近更新 更多