我想为瘦客户端开发html5 SPA应用程序。无法在其上启动任何Web服务器。而且我不能在没有Web服务器的情况下进行路由工作。
我的index.html
<!doctype html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<script src="app.js"></script>
<title></title>
</head>
<body style="background-color: white;">
<h1>Index</h1>
<a id="link" href="/login">Go to login</a>
<div ng-controller="HomeCtrl">
<ul ng-repeat="number in numbers" >
<li>{{number}}</li>
</ul>
</div>
</body>
</html>
我的app.js.
angular.module('app', []).
config(function($routeProvider) {
$routeProvider.
when('/', {controller: HomeCtrl, templateUrl: 'index.html'}).
when('/login', {controller: LoginCtrl, templateUrl: 'login.html', resolve: function() {}}).
otherwise({redirectTo:'/'});
});
function HomeCtrl($scope) {
$scope.numbers = [1,2,3,4,5];
}
function LoginCtrl($scope) {
}
我正在Chrome中的计算机上本地测试此代码。数据绑定的工作方式与魅力相似,但登录页面的链接却没有。它通向{X}:\ login。所以我的问题是:是否有可能使它与Web服务器一起使用?其次,我缺少完成它的工作?
您需要使用脚本标记将模板放在index.html中,以便angular不再需要生成AJAX请求来获取它们。
<script type="text/ng-template" id="home.html">
This is the content of the template
</script>
过了一会儿,我做到了。
起初,我将这篇文章移到了单独的文件中
<div ng-controller="HomeCtrl">
<ul ng-repeat="number in numbers" >
<li>{{number}}</li>
</ul>
</div>
其次,在 index.html
我添加了这个div
<div ng-view></div>
它用作视图占位符。
现在 index.html
如果您熟悉asp.net,则用作“母版页”或“布局”。单击链接时,templateUrl文件的内容将插入占位符div。
这样做的一个缺点是url应该是这样的 <a href="#/login"></a>
您需要使用脚本标记将模板放在index.html中,以便angular不再需要生成AJAX请求来获取它们。
<script type="text/ng-template" id="home.html">
This is the content of the template
</script>
过了一会儿,我做到了。
起初,我将这篇文章移到了单独的文件中
<div ng-controller="HomeCtrl">
<ul ng-repeat="number in numbers" >
<li>{{number}}</li>
</ul>
</div>
其次,在 index.html
我添加了这个div
<div ng-view></div>
它用作视图占位符。
现在 index.html
如果您熟悉asp.net,则用作“母版页”或“布局”。单击链接时,templateUrl文件的内容将插入占位符div。
这样做的一个缺点是url应该是这样的 <a href="#/login"></a>
Angular是一个客户端JS框架,因此它不需要Web服务器。除了添加ng-view(正如您已经想到的那样),您需要在前面添加一个hashbang(#/login
),除非你使用的是html5mode。
因此,在URL中使用hashbang不是一个缺点,它是一个选项。
这里有一些代码 http://docs.angularjs.org/api/ng。$路线
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
我认为同样适合你。
本期的解决方案[ 仅支持HTTP的跨源请求 ]对我有用。
但我真的不明白如何使用ngView和ngRoute在没有Web服务器的情况下让它工作?
您配置ngRoute以获取index.html之外的login.html,这意味着您正在使用AJAX服务来加载文件,但如果没有Web服务器,AJAX服务将无法运行。这就是我得到我的问题的原因。