您需要区分 Laravel 应用程序的路由和 Angular 应用程序的路由。
定义一个路由来显示 Angular 应用程序
// Http/routes.php
Route::get('/{js_route}', function() {
return view('application');
})->where('js_route', '(.*)'); // Allow multiple URI segments
此路由允许斜杠使用 ngRoute 进行路由,它应该是您的 routes.php 中最后定义的。
它只会渲染一个模板,用于显示你的真实 Angular 应用程序。
// views/application.blade.php
<html>
<body>
<div class="container">
<div ng-view></div> <!-- Here will come your partial views -->
</div>
</body>
</html>
使用 Angular 进行真正的应用程序路由
现在,使用 ngRoute 定义应用程序的路由并在它们之间导航。
// public/js/src/app.js
$routeProvider
.when('/', {
templateUrl: 'Default/index.html', // A simple HTML template
});
// ...
在 Laravel 中创建 API 端点
您将在 Angular 应用程序中使用 XHR 从 Laravel 应用程序中检索数据。
为此,只需在相应的方法(即 GET、POST)中定义新路由,并创建相应的控制器/动作。
// Http/Controller/FooController.php
class FooController extends \BaseController {
/**
* List all Foo entities in your app
*
* @return Response
*/
public function index()
{
return Response::json(Foo::get());
}
}
// Http/routes.php
Route::get('/api/foo', 'FooController@index')
创建服务/工厂以检索您的数据
// public/js/src/app.js
(function (app) {
function FooService($http, $q) {
this.getFoos = function() {
return $http.get('/api/foo');
};
}
app.service('Foo', FooService);
})(angular.module('yourApp'));
这样,您可以从 laravel 路由中检索数据,而无需直接浏览路由。
// public/js/src/app.js
function MainCtrl($scope, $http) {
$scope.listFoo = function() {
$http.getFoos()
.then(function(response) {
$scope.foos = response.data;
}, function(error) {
console.log(error);
});
};
}
app.controller('MainController', MainCtrl);
使用您的应用程序
现在,您可以仅使用 javascript 路由在应用程序中导航,并使用 Laravel 路由从后端检索数据。