【问题标题】:Loading a html file through angular's ui-router using templateUrl使用 templateUrl 通过 Angular 的 ui-router 加载 html 文件
【发布时间】:2016-12-22 06:19:43
【问题描述】:

我正在使用 Angular UI-Router 来声明状态。我的状态设置正确,并且 Angular 在我的页面上工作,但模板 html 文件未正确加载。当我这样做时

template: 'template: 'js/timer/timer.template.html'

在我的控制器中,文本(上面的路径)按预期呈现,但是当我将其切换到

templateUrl: 'js/timer/timer.template.html',

timer.template.html 文件未呈现。不过,我的 index.html 文件似乎被加载了两次。一次如预期,第二次被复制并注入<ui-view> </ui-view> 这是我的 index.html 文件:

<!DOCTYPE html>
<html>
    <head>
        <base href="/">
        <link rel="stylesheet" href="index.css">

        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
        <script src="https://unpkg.com/angular-ui-router@0.3.2/release/angular-ui-router.min.js"> </script>
        <script src="main.js"> </script>
    </head>

    <body ng-app='PomodoroTimer'>
        <ui-view> </ui-view>
        <p>1+2={{1+2}}</p>
    </body>
</html>

当我转到 localhost:1337/timer (我设置的状态)时,这个 index.html 文件似乎得到了两次,一次按预期,然后再次在 ui-view 中,显示 1+2=3两次。

这是我的 timer.state.js 文件。我尝试过使用不同的路径,但似乎没有任何东西指向正确的 html 文件。

app.config(function($stateProvider) {
    $stateProvider.state('timer', {
        url: '/timer',
        templateUrl: 'js/timer/timer.template.html',
        controller: 'TimerCtrl'
    });
});

我是否缺少关于 UI-Router 或 templateUrl 的某些内容,或者我没有正确设置的内容?我正在使用 express 来处理路由,但只是将所有请求发送到 /* 到 index.html 文件,以便 UI-Router 可以接管。我是否必须像处理 css 文件一样通过 express 静态提供模板 html 文件?

这里是 timer.template.html,其中 timerMessage 在控制器的$scope 上定义

<p>This is the timer state and message is: {{timerMessage}}</p>

这里是 github 链接:github.com/sbernheim4/pomodoro-timer

【问题讨论】:

  • 当你点击localhost:1337/js/timer/timer.template.html时你得到你的模板了吗?
  • 不,我没有,index.html 文件已加载并显示1+2=3
  • 正确。所以这就是你的问题。您需要更改您的服务器或构建过程,以便您为模板指定的 url 实际加载模板
  • 知道了。谢谢

标签: javascript angularjs angular-ui-router


【解决方案1】:

是的,您的最后一段透露了正在发生的事情。 节点无法将路径 js/timer/timer.template.html 匹配到任何路由,因此 catch all 被执行(返回索引而不是实际文件)。

这是一个如何为 html5mode 配置 Express 的示例:

//Look for statics first - this is important!
var oneHour = 3600 * 1000;
app.use(express.static(path.join(__dirname, 'public'), {maxAge: oneHour}));
//Return the index for any other GET request
app.get('/*', function (req, res) {
    res.sendFile('index.html', {root: path.join(__dirname, 'public')});
});

所以是的,基本上你必须像处理 js 和 css 文件一样提供模板。

【讨论】:

  • 知道了。但是,如果我有一堆文件夹,每个文件夹都包含一个状态、控制器和模板 html 文件,我应该怎么做,我是否需要静态地为每个文件夹提供服务,或者最好将我所有的 html 文件放在一个单独的文件夹中从他们的控制器和状态 js 文件中
  • 上面的例子是递归的,所以任何嵌套在/public中的目录和文件都会被静态导出。
猜你喜欢
  • 1970-01-01
  • 2016-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-03
相关资源
最近更新 更多