如何将 Laravel 变量传递到我的 AngularJS 视图中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29246298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:12:43  来源:igfitidea点击:

How can I pass a Laravel variable into my AngularJS view?

javascriptphpangularjslaravel

提问by Andrew

I am building a small photo application to learn AngularJS 1.3. I come from a PHP background so conceptually this is rather different for me :)

我正在构建一个小的照片应用程序来学习 AngularJS 1.3。我来自 PHP 背景,所以从概念上讲,这对我来说是相当不同的 :)

I'd like to pass a variable (the URL of my photos folder) into my AngularJS view (an .html file). How can I do this?

我想将一个变量(我的照片文件夹的 URL)传递到我的 AngularJS 视图(一个 .html 文件)中。我怎样才能做到这一点?

In other words, what's the best practice for passing application constants from PHP to AngularJS ngRoute views?

换句话说,将应用程序常量从 PHP 传递到 AngularJS ngRoute 视图的最佳实践是什么?

Here's the code:

这是代码:

Laravel Controller Method

Laravel 控制器方法

public function showHome()
{
    $upload_url = Config::get('app.url');
    return View::make('home')->with('upload_url', $upload_url."photos/");
}

Blade Template

刀片模板

$upload_urlis the variable I would like to use in my AngularJS view (index.html).

$upload_url是我想在我的 AngularJS 视图 ( index.html) 中使用的变量。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
        <title>Test Application</title>
    </head>
    <body ng-app="app" ng-controller="mainController">

        <div class="container">

            <p>The location of the photo files is:</p>
            <p>{{ $upload_url }}</p>

            <ng-view></ng-view>

        </div>

        {{ HTML::script('assets/js/jquery-2.1.1.min.js') }}
        {{ HTML::script('https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js') }}
        {{ HTML::script('http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js') }}
        {{ HTML::script('app/controllers/mainController.js') }}
        {{ HTML::script('app/services/photoService.js') }}
        {{ HTML::script('app/app.js') }}

    </body>
</html>

App.js

应用程序.js

var constantsHelper = {};

var app = angular.module('app', ['ngRoute', 'mainController', 'photoService']);

app.config(function($routeProvider){
    $routeProvider.when("/",
        {
            templateUrl: "app/views/home.html",
            controller: "mainController"
        }
    );
});

Main Controller (mainController.js)

主控制器(mainController.js)

angular.module('mainController', [])

.controller('mainController', function($scope, $http, Photo) {

    Photo.get()
        .success(function(data) {
            $scope.photos = data;
        });

});

Photo Service (photoService.js)

照片服务 (photoService.js)

angular.module('photoService', [])

.factory('Photo', function($http) {

    return {

        // Get all the photos
        get : function() {
            return $http.get('/api/photos');
        }

    }

});

...and finally my Angular view (home.html)

...最后是我的 Angular 视图 (home.html)

I'd like to prefix photo.filenamewith the $upload_urlvalue from my blade template (which comes from the showHome()method of my Laravel controller).

我想以我的刀片模板(来自我的 Laravel 控制器的方法)中photo.filename$upload_url值作为前缀showHome()

<div class="photo" ng-repeat="photo in photos">

   <div class='row'>
       <div class='col-md-10 col-md-offset-1'>
           <div class='loaded-image mb25'>
               <img src='{{ photo.filename }}'>
               <p>{{ photo.description }}</p>
           </div>
       </div>
   </div>

</div>

Thanks! Any pointers that can put me on the right path are appreciated :)

谢谢!任何可以让我走上正确道路的指针都值得赞赏:)

Edit:

编辑:

I have it working, but no idea if this is the best practice!

我有它的工作,但不知道这是否是最佳实践!

I've added this to the bottom of my blade template:

我已将此添加到我的刀片模板底部:

<script>
    constants = {};
    constants.upload_url = {{ $upload_url }}}";
</script>

And modified the main controller to pass the constants using $scope.

并修改主控制器以使用$scope.

angular.module('mainController', [])

.controller('mainController', function($scope, $http, Photo) {

    Photo.get()
        .success(function(data) {
            $scope.photos    = data;
            $scope.constants = constants;
            console.log(constants);
        });

});

Then I can access the upload URL in index.htmlsimply with {{ constants.upload_url }}.

然后我可以index.html简单地使用{{ constants.upload_url }}.

So... it works but I have no idea of this is hacky or not ;)

所以......它有效,但我不知道这是否是hacky ;)

Any input would be appreciated!

任何输入将不胜感激!

回答by yazaki

I wonder whether this would be the best practice or not. However If the value doesn't need to be secure, one of the most simple way to pass constant values from server is something like this.

我想知道这是否是最佳实践。但是,如果值不需要是安全的,那么从服务器传递常量值的最简单方法之一就是这样。

In html.

在 HTML 中。

<script type="text/javascript">
    var _config = {
        key1: server_value1,
        key2: server_value2
    };
</script>

In angular module run method.

在 angular 模块运行方法中。

angular.module('yourapp', [])
    .run(function($rootScope) {
        $rootScope.config = _config;
    });

In your controller.

在您的控制器中。

console.log($scope.config);

回答by diegoaguilar

Did you managed to have Angular and Blade syntax in order? In my case I changed what Laravel uses for echoing variables and evaluating expressions this way setting at routes.php:

您是否设法按顺序使用 Angular 和 Blade 语法?在我的例子中,我改变了 Laravel 用于回显变量和评估表达式的方式设置为routes.php

Blade::setContentTags('[[', ']]');        // for variables and all things Blade
Blade::setEscapedContentTags(',.', '.,');   // for escaped data

I'm not sure about how a good practice is but time to time I set some ng-initdirectives this way:

我不确定一个好的做法是什么,但我不时以ng-init这种方式设置一些指令:

Blade template

刀片模板

<div ng-controller="mainController" ng-init="constants={upload_url:'[[$upload_url]]'}">
  ...
</div>

View

看法

The way I obtain a rendered view this way:

我以这种方式获得渲染视图的方式:

<div ng-controller="mainController" ng-init="constants={upload_url:'some_url_string'}">
 ...
</div>

Then you could reach it from a controller and use it for ng-Routethis way:

然后你可以从控制器访问它并以ng-Route这种方式使用它:

$scope.constants.upload_url