直接调用partial时的角度加载主模板

时间:2015-07-31 09:41:23

标签: angularjs laravel-5

我正在使用AngularJS和Laravel构建一个用于API交互的应用程序。我有一个主模板文件,说index.html里面有ng-view

客户列表视图的网址:http://example.com/#customers其中,客户是部分视图网址。

后来我将应用程序切换到html5mode,以便我可以在没有#部分的情况下调用它,例如。 http://example.com/customers

问题

如果它在Angular范围内调用它确实有效,但是如果我直接调用URL,它只会加载客户列表视图HTML片段(没有主模板和脚本)并打破应用程序。

无论如何都要解决这个问题?

2 个答案:

答案 0 :(得分:0)

Okay, I'll try to give an answer as it's a bit too long for a comment.

I'm a newbie to AngularJS myself, but as far as I can interprete your description, you're using the same URLs for the features in your frontend app as in your API. The difference is, that your API is served by your web server, but the frontend pages are served by Angular.

So for simplicity, I'll assume that your initial Angular page (index.html) is reachable through your main URL (e.g. www.example.com). All subdomains of example.com are only for API calls. Means if you switch the page within the frontend app, Angular catches this URL state change and serves whatever you requested by doing a background request (AJAX), but that also means you still have your index.html present in the browser (with another subview ofc).

By refreshing the page (or calling the URL directly), you're asking the server for a completely different resource. It should be obvious, that www.example.com serves something different than www.example.com/api/random/resource. Before you don't have the index.html loadet in your browser, Angular is not loaded as well and cannot catch URL state changes to prevent the default browser behavior (namely requesting exactly this resource from the server). So from the server point of view, you're not requesting the main page, but an API resource.

So what I would suggest as solution, is quite straight forward. As I already mentioned, I'm new to AngularJS myself, but as far as I know (and could read on the web), Angular works with AJAX calls in background (makes sense, does it?). So you could simply use a middleware in your Laravel application, which decides, if a request is AJAX based or not. This middleware could then, if it is no AJAX call, supply the main page (without changing the actual URL!). In succession, the Angular app would still have the requested URL as state and could serve whatever you actually want it to serve.

I cannot supply you any code, because I don't have the time at the moment, but I think you don't really need all that much and as far as I remember, there is already a middleware handling some AJAX stuff... maybe you have a look into this one. If you find a solution within your code, feel free to share!

答案 1 :(得分:0)

经过研究,我发现最合适的方法是使用.htaccess路由到主模板。以下将完成这项工作。

RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} -s [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*) index.html [NC,L]