简体   繁体   English

如何将对象从symfony控制器传递到angularjs,以便使用它定义变量?

[英]How to pass an object from symfony controller to angularjs in order to define a variable with it?

I need to pre fill a TextType with some data initially but Angularjs keeps resetting my TextType to empty, even when I set value attribute to it... So, how can I initially define it with that value on page load? 我需要在开始时用一些数据预填充TextType,但是Angularjs仍将我的TextType重置为空,即使我为它设置了value属性也是如此...那么,如何在页面加载时最初用该值定义它呢? I need this keyword model to be set with the user email, adding value as an attribute doesn't work... 我需要使用用户电子邮件设置此关键字模型,将值添加为属性不起作用...

{{ form_row(form.keyword,  {'attr': {'ng-model': 'keyword'}} )}}

My user is sent in the controller as an argument. 我的用户作为参数发送到控制器中。

public function addAction(User $user = null, Request $request)

And this is my Angularjs controller, what I wish to achieve is initially declare keyword with the user email. 这是我的Angularjs控制器,我希望实现的目标是首先在用户电子邮件中声明关键字。

//$scope.keyword = $user.email.

What I am doing right now is initially setting it to empty, and that's why it keeps presetting the value attribute to empty. 我现在正在做的是将其最初设置为空,这就是为什么它会继续将value属性预置为空的原因。

In your controller you have to use the Symfony Serializer component to serialize your user then pass this serialized object as attribute to your twig and deserialize it in javascript: 在您的控制器中,您必须使用Symfony序列化器组件来序列化用户,然后将此序列化的对象作为属性传递给树枝,并在javascript中反序列化:

use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class DefaultController extends AbstractController {
    ...
    public function addAction(User $user = null, Request $request, SerializerInterface $serializer){
        ...
        $serializedUser = $serializer->serialize($user, 'json');
        return $this->render('default/add_action.html.twig', [
            'user' => $serializedUser,
            'form' => $form->createView()
        ]);
    }

Beware that if you have entity associations in your user entity you may face circular reference problems. 请注意,如果用户实体中有实体关联,则可能会遇到循环引用问题。

In this case you have to use serialization groups (doc here ) when serializing your user like this: 在这种情况下,您像这样序列化用户时必须使用序列化组(在doc ):

$serializedUser = $serializer->serialize($user, 'json', ['groups' => ['add-action']]);

Finally in your twig, you'll have to do something like that in your container div: 最后,在树枝中,您必须在容器div中执行以下操作:

<div id="form-container" ng-init="user = {{ user|e('html_attr') }}">

Try this: 尝试这个:

$scope.keyword = "{{ user.email }}";

Since twig and Angularjs uses the same interpolation "{{}}". 由于twig和Angularjs使用相同的插值“ {{}}”。 You can configure angularjs to use other interpolation string such as "[[ ]]"; 您可以将angularjs配置为使用其他插值字符串,例如“ [[]]”;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM