mardi 24 mars 2015

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('http://ift.tt/1vCsXos') }}
{{ HTML::script('http://ift.tt/1ADREN3') }}
{{ 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 :)





Aucun commentaire:

Enregistrer un commentaire