Best way to pass variables from Symfony2 to Angular scope
You can declare variables directly in ng-init, so:
<div ng-controller="myCtrl" ng-init="myModel.someVar='{{ twig_object | json_encode() }}';">
I'm more used to Razor in ASP.Net MVC but I assume the same principle applies here with Symfony2.
Also remember the double dot rule, you don't want value's declared directly on $scope.
Well your options are limited in this case. If you don't want to make extra call then you will have to inject data into page as global variable (@JMK gives one more useful way with ngInit
). It can be simple variable, but I find it more convenient to write it in form of some object and set a constant service from this global value. After that this constant can be used throughout the app.
<script>window.config = {{ twig_object | json_encode() }};</script>
Then create a constant (or value
):
app.constant('config', {data: window.config});
and in controller
app.controller('myCtrl', ['$scope', 'config', function($scope, config) { $scope.init = function () { $scope.someVar = config.someVar; };}]);