use*_*374 9 .htaccess html5 hashtag angularjs-routing
我想使用Angularjs从URL中删除#hash $locationProvider.html5Mode(true).
示例:显示地址栏http://localhost/shop而不是http://localhost/#/shop.
一切都运作良好,直到刷新页面.如果我刷新,则会加入以下Laravel路由(在routes.php中定义)
Route::resource('shop', 'ShoppingController')
Run Code Online (Sandbox Code Playgroud)
不是AngularJS路线(在app.js中定义)
$routeProvider.when('/shop', {
templateUrl: 'templates/shop.html',
controller: 'ShoppingController'
});
Run Code Online (Sandbox Code Playgroud)
我的代码:
routes.php(Laravel Routes)
Route::get('/', function() {
return View::make('index');
});
Route::resource('shop', 'ShoppingController');
Run Code Online (Sandbox Code Playgroud)
app.js(AngularJS路线)
var app = angular.module('shoppingApp',['ngRoute','SharedServices']);
app.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/shop', {
templateUrl: 'templates/shop.html',
controller: 'ShoppingController'
});
$routeProvider.otherwise({ redirectTo: '/' });
$locationProvider.html5Mode(true);
});
Run Code Online (Sandbox Code Playgroud)
我的目录结构:
Project
/app
/...
/views
-index.php (single page application file)
-routes.php (Laravel routes)
/public
/...
/js
-angular.js
-app.js
-index.php (Laravel index file)
Run Code Online (Sandbox Code Playgroud)
尝试的解决方案:
重写htaccess文件,以便将所有请求重定向到index.php(单页应用程序文件,AngularJS将从该文件中接管路由).问题:通过这种方式,Laravel路由(Route :: resource('shop','ShoppingController'); - 与数据库交互所必需的)变得无法访问AngularJS $ http服务:
app.js
app.controller("ShoppingController", function($scope, $http) {
$http.get('/shop', { cache: true}).
success(function(data, status) {
$scope.items = data
}).
error(function(data, status) {
console.log('Status: ' + status);
});
});
Run Code Online (Sandbox Code Playgroud)
问题: 如何解决路由问题,以便在刷新localhost/shop时访问AngularJS路由,而不是Laravel路由?
小智 7
从我读到的内容来看,当您刷新页面时,Laravel似乎正在读取修改后的路线.在这种情况下,你应该让Laravel继续制作原始视图,即使它本来是404重定向.
尝试在Laravel端添加以下内容(例如routes.php)
App::missing(function($exception)
{
return View::make('index');
});
Run Code Online (Sandbox Code Playgroud)
注意:您可能希望使用AngularJS的路由来处理未找到的页面.
小智 5
更好的解决方案是以这种方式重定向:
'重定向::到('///'.Request :: path())'
当您刷新或直接转到URI时:
最终解决方案
App::missing(function($exception) {
return Redirect::to('/#/' . Request::path());
});
Run Code Online (Sandbox Code Playgroud)