Best way to pass variables from Symfony2 to Angular scope

As a normal scenario that many other developers encounter, we have mature Symfony2 / TWIG-based applications, and some of the html.twig templates are too overloaded with jQuery code and difficult to maintain. How about throwing jQuery and using Angular? Assuming I have some basic knowledge of Angular modules, controllers, services, and a deep understanding of Symfony2 / TWIG, the problem with my fist is , what is the best way to pass variables from my existing controller / twig patterns for Angular controllers?

I do not want to load the region through a separate JSON call and a separate controller in Symfony2. I just want to use the existing variables that I have on the branch.

One way to do this is to declare some global js variables:

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

a then do smth like

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

and in the controller

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

But it seems too ugly for me (3 steps) Can it be simplified at least or differently?

+6
source share
3 answers

You can declare variables directly in ng-init, therefore:

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

Also remember the double point rule, you do not want the value to be declared directly in the $ scope.

+7
source

Well, your options are limited in this case. If you do not want to make an additional call, you will have to enter data on the page as a global variable (@JMK provides another useful way with ngInit ). It may be a simple variable, but it’s more convenient for me to write it in the form of some object and establish a permanent service from this global value. After that, this constant can be used throughout the application.

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

Then create a constant (or value ):

 app.constant('config', {data: window.config}); 

and in the controller

 app.controller('myCtrl', ['$scope', 'config', function($scope, config) { $scope.init = function () { $scope.someVar = config.someVar; }; }]); 
+4
source

Actually, I think this is the easiest working solution:

 <div ng-init='somevar = {{ somevar|raw|replace({"'":"\\'"}) }}'> 
+2
source

Source: https://habr.com/ru/post/982464/


All Articles