Blade 中使用 AngularJS

ravel 的 Blade 模版引擎和 AngularJS 的模版引擎使用同样的变量显示方法如下:

{{ variableName }}

解决方法

下面几种解决方法:
  1. 修改 Laravel Blade 的变量解析方式;
  2. 修改 AngularJS 的变量解析方式;
  3. 在 Blade 里使用 @{{ variableName }} , 跳过 Blade 的变量解析;
  4. 在 Blade 模版里面使用 include去包含 Angular 模版 (推荐这种方法);
  5. 完全不使用 Blade.

1. 修改 Laravel Blade 的变量解析方式

使用以下方法修改:
Blade::setContentTags('<%', '%>'); // for variables and all things BladeBlade::setEscapedContentTags('<%%', '%%>'); // for escaped data    
上面的修改会影响 Blade 模版引擎的行为:
  • 变量使用输出 - <% $variable %>
  • 注释 <%-- $variable --%>
  • 需要转义的变量数据 <%% $variable %%>
代码可以放到 routes.php文件里面.

2. 修改 AngularJS 的变量解析方式

在初始化 Module的时候, 调用 $interpolateProvider进行设置:
var sampleApp = angular.module('sampleApp',[],function($interpolateProvider){
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');});
上面的代码会让 AngularJS 使用 <% variableName %>这种方法去解析变量.

3. 在 Blade 里使用 @{{ variableName }} , 跳过 Blade 的变量解析

在写变量的时候, 可以使用在前面加 @的方法跳过解析:
@{{ variableName }}
上面的代码你如果写在 Blade 模版里面的话, 应用输出 HTML 会是:
{{ variableName }}

4. 在 Blade 模版里面使用 include去包含 Angular 模版 (推荐这种方法)

如以下代码, 是在文件 app/views/index.blade.php Blade 模版里面, 注意看 @include的使用:
<html>
<head>
    <title>Fancy Laravel and Angulartitle>
    
    <scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js">script>
head>
<body>

    @include('angular-stuff'); 
    
使用 @include('angular-stuff')会加载 app/views/angular-stuff.php文件.
推荐使用此方法, 原因是能够让代码更加模块化, 并且能同时兼并 Laravel Blade 和 Angular 的好处.

5. 完全不使用 Blade.

完全的把 Laravel App 作为 API 服务器, 前端和后端分离.
// app/routes.phpRoute::get('/',function(){returnView::make('index'); // app/views/index.php});