我正在尝试仅使用 javascript 和 AngularJS 覆盖我的单页应用程序的一部分。
覆盖基于子域。
每个子域都指向同一个文档根。
控制器.js
controller('AppController', ['$scope','$route','$routeParams','$location', function($scope, $route, $routeParams, $location) {
$scope.$on("$routeChangeSuccess",function( $currentRoute, $previousRoute ){
render();
});
var render = function(){
//Is it actually a subdomain?
if($location.host().split(".",1).length>2){
//Use subdomain folder if it is.
var url = "views/"+$location.host().split(".",1)+"/"+$route.current.template;
var http = new XMLHttpRequest();
http.onreadystatechange=function(){
if (http.readyState==4){
//If there isn't an overwrite, use the original.
$scope.page = (http.status!=404)?url:("views/"+$route.current.template);
}
}
http.open('HEAD', url, true);
http.send();
}
else{
//Else we are on the parent domain.
$scope.page = "views/"+$route.current.template;
}
};
}])
配置.js
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/', {
template: 'home.html'
});
$routeProvider.when('/services', {
template: 'services.html'
});
$routeProvider.otherwise({redirectTo: '/'});
}]);
索引.html
<html lang="en" ng-app="myApp" ng-controller="AppController">
<body>
<div ng-include src="page" class="container"></div>
</body>
</html>
因为这是一个单页应用,所以当你直接点击一个 URL 时,它会变成404
. 这就是我们在服务器上应用重写规则的原因。就我而言,我使用的是 nginx:
location / {
try_files $uri /index.html;
}
当我不在子域上时,这很有效,但是我也没有发送XMLHttpRequest
. 当我确实使用子域时,现在我们需要检查是否有覆盖。
这里棘手的部分是重写规则强制 XMLHttpRequest 返回 200。
关于如何吃蛋糕和吃蛋糕的想法?