Best way to pass variables from Symfony2 to Angula

2019-06-18 15:26发布

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?

3条回答
走好不送
2楼-- · 2019-06-18 15:55

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.

查看更多
走好不送
3楼-- · 2019-06-18 16:07

Actually I think this is the easiest working solution:

<div ng-init='somevar = {{ somevar|raw|replace({"'":"\\'"}) }}'>
查看更多
太酷不给撩
4楼-- · 2019-06-18 16:21

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;
    };
}]);
查看更多
登录 后发表回答