最好的办法,从Symfony2的传递变量角度范围 [英] Best way to pass variables from Symfony2 to Angular scope
问题描述
作为一种常见的场景,许多其他开发商面临 - 我们有一个基于Symfony2中/嫩枝成熟的应用,以及一些html.twig模板得到太多的使用jQuery code和难以维持超载。
关于扔掉了jQuery,并用角是什么?
只要我对角模块,控制器,服务和范围,以及Symfony2中/树枝深入了解一些基本的知识,我的拳头的问题是 - 什么是从我现有的控制器/枝模板的角度传递变量的最佳方式控制器?
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?
我不希望通过单独调用JSON和Symfony2中一个单独的控制器来加载范围。只是想用现有变量我在树枝。
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.
做的一种方法是声明一些全局变量JS:
One way to do is declare some global js variables:
<script>
var window.someVar = {{ twig_object | json_encode() }};
</script>
的话就不便像
<div ng-controller="myCtrl" ng-init="init()">
<div ng-model="someVar"> .... </div>
</div>
和控制器中
app.controller('myCtrl', ['$scope', function($scope) {
$scope.init = function () {
if (window['someVar']) {
$scope['someVar'] = window['someVar'];
}
};
不过,这似乎太丑陋了,我(3步)
可它至少可以简化或做另一种方式?
But this seems too ugly for me (3 steps) May it be simplified at least or done another way?
推荐答案
您可以直接在NG-初始化声明变量,所以:
You can declare variables directly in ng-init, so:
<div ng-controller="myCtrl" ng-init="myModel.someVar='{{ twig_object | json_encode() }}';">
我更习惯剃刀在ASP.Net MVC但我相信同样的原则也适用于这里的Symfony2。
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.
这篇关于最好的办法,从Symfony2的传递变量角度范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!