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?
You can declare variables directly in ng-init, so:
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.
Actually I think this is the easiest working solution:
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.Then create a constant (or
value
):and in controller