我想使用 Angularjs 的 $locationProvider.html5Mode(true)
从 URL 中删除 # 散列。
示例:地址栏显示 http://localhost/shop
而不是 http://localhost/#/shop
。
一切正常,直到我刷新页面。如果我刷新,将访问以下 Laravel 路由(在 routes.php 中定义)
Route::resource('shop', 'ShoppingController')
不是 AngularJS 路由(在 app.js 中定义)
$routeProvider.when('/shop', {
templateUrl: 'templates/shop.html',
controller: 'ShoppingController'
});
我的代码:
routes.php(Laravel 路由)
Route::get('/', function() {
return View::make('index');
});
Route::resource('shop', 'ShoppingController');
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);
});
我的目录结构:
Project
/app
/...
/views
-index.php (single page application file)
-routes.php (Laravel routes)
/public
/...
/js
-angular.js
-app.js
-index.php (Laravel index file)
尝试过的解决方案:
重写 htaccess 文件,以便所有请求都重定向到 index.php(单页应用程序文件,AngularJS 将从中接管路由)。问题:这样,AngularJS $http 服务就无法访问 Laravel 路由(Route::resource('shop', 'ShoppingController'); - 与数据库交互所必需的):
应用程序.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);
});
});
问题: 如何解决路由问题,以便在刷新 localhost/shop 时访问 AngularJS 路由,而不是 Laravel 路由?
最佳答案
从我读到的内容来看,当您刷新页面时,Laravel 似乎正在读取修改后的路由。在这种情况下,你应该让 Laravel 继续创建原始 View ,即使它会是 404 重定向。
尝试在 Laravel 端的某处添加以下内容(例如 routes.php)
App::missing(function($exception)
{
return View::make('index');
});
注意:您可能希望 AngularJS 的路由使用 .otherwise 来处理未找到的页面。
关于html - HTML5 模式下 AngularJS 和 Laravel 4 路由冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21357258/