Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 :)

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?

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

Here's the code:

Laravel Controller Method

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

Blade Template

$upload_url is the variable I would like to use in my AngularJS view (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

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)

angular.module('mainController', [])

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

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

});

Photo Service (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)

I'd like to prefix photo.filename with the $upload_url value from my blade template (which comes from the showHome() method of my Laravel controller).

<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.

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.html simply with {{ constants.upload_url }}.

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

Any input would be appreciated!

like image 719
Andrew Avatar asked Mar 25 '15 02:03

Andrew


People also ask

Can we use angular and laravel together?

you can use both angular and laravel separately. And call laravel api from angular.

How do you share data between controller and view in AngularJS?

To create a module in AngularJS, we use angular. module("app", []); syntax. 14) Which of the following is used to share data between controller and view in AngularJS? Answer: B: "using services" is the correct answer.

Does AngularJS work with PHP?

If you're wondering whether you can use PHP alongside Angular, the answer is yes. But Angular will still need a separate client-server architecture. In general, PHP runs on the server-side while Angular runs on the client-side. Therefore, to establish communication between them, you would need an API.


2 Answers

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.

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

In angular module run method.

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

In your controller.

console.log($scope.config);
like image 153
yazaki Avatar answered Oct 03 '22 00:10

yazaki


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:

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-init directives this way:

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-Route this way:

$scope.constants.upload_url
like image 26
diegoaguilar Avatar answered Oct 02 '22 22:10

diegoaguilar