我正在使用 Angular UI-Router 来声明状态。我的状态设置正确, Angular 在我的页面上工作,但模板 html 文件未正确加载。当我做的时候
template: 'template: 'js/timer/timer.template.html'
在我的 Controller 中,文本(上面的路径)按预期呈现,但是当我将其切换到
templateUrl: 'js/timer/timer.template.html',
timer.template.html 文件没有被渲染。但是,我的 index.html 文件似乎被加载了两次。一次按预期进行,第二次将其复制并注入(inject)到 <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
上 Controller
<p>This is the timer state and message is: {{timerMessage}}</p>
这是 github 链接:github.com/sbernheim4/pomodoro-timer
最佳答案
是的,您的最后一段泄露了正在发生的事情。
节点无法将路径 js/timer/timer.template.html
与任何路由匹配,因此 catch all 被执行(返回索引而不是实际文件)。
这是一个如何为 html5 模式配置 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 文件一样提供模板。
关于javascript - 使用 templateUrl 通过 angular 的 ui-router 加载 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41272757/