javascript と AngularJS のみを使用して、単一ページ アプリの一部を上書きしようとしています。
上書きはサブドメインに基づいています。
すべてのサブドメインが同じドキュメント ルートを指しています。
controllers.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;
}
};
}])
config.js
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/', {
template: 'home.html'
});
$routeProvider.when('/services', {
template: 'services.html'
});
$routeProvider.otherwise({redirectTo: '/'});
}]);
index.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 を返すように強制されていることです。
ケーキを食べて食べる方法についてのアイデアはありますか?