Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to pass variables from Symfony2 to Angular scope

As a common scenario that many other developers face - we have a mature application based on Symfony2 / TWIG, and some of the html.twig templates got too much overloaded with jQuery code and hard to maintain. What about throwing away jQuery, and use Angular ? Provided I have some basic knowledge about angular modules, controllers, services and scope, and a deep knowledge of Symfony2/TWIG, my fist problem is - what is the best way to pass variables from my existing controllers/twig templates to angular controllers?

I don't want to load scope through separate JSON call and a separate controller in Symfony2. Just want to use existing variables I have in twig.

One way to do is declare some global js variables:

<script>
var window.someVar = {{ twig_object | json_encode() }};
</script>

an then do smth like

<div ng-controller="myCtrl" ng-init="init()">
<div ng-model="someVar"> .... </div>
</div>

and in controller

app.controller('myCtrl', ['$scope', function($scope) {
$scope.init = function () {
    if (window['someVar']) {
        $scope['someVar'] = window['someVar'];
    }
};

But this seems too ugly for me (3 steps) May it be simplified at least or done another way?

like image 994
Ross Ivantsiv Avatar asked Feb 13 '15 20:02

Ross Ivantsiv


1 Answers

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.

like image 115
JMK Avatar answered Oct 13 '22 12:10

JMK