I have been facing a lot of issues myself trying to make Symfony and AngularJS work together. However while working on it I learned a few things which may help you:
- To separate the AngularJS expressions
{{ variable }}
from twig curly braces you have three alternatives :
a). Use the quotes around the AngularJS expressions {{ '{{ variable }}' }}
b). Surround your AngularJS code with {% verbatim %} your code {% endverbatim %}
c). Use AngularJS interpolateProvider
service
angular.module('myApp', []).config(function($interpolateProvider){
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
});
- In the js file, twig can’t generate the URL for you. For this you can use "friendsofsymfony/jsrouting-bundle". After installing it you can use it as:
$http.get(Routing.generate('route_name', {'id':id}));
This may not work for you for submission, why? One thing you should know about the $http.post is that it dosen’t send the data as “Form Data” but as “Request Payload”, which is the normal way to transmit data via HTTP POST. The problem is that this “normal way” is not equivalent to a form submission, which causes problem in interpreting data with the Symfony Request object.
use this instead:
$http.put(url, $.param({foo: 'bar'}), {
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
When you want to know if a request is an AJAX request within the controller, we usually use the isXMLHttpRequest() method. The problem is that Angular don’t identify its requests as an XMLHttpRequest requests. Use this:
var app = angular.module('myModule', []);
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);
While creating forms you can choose to display the form through AngularJS and let Symfony Form to handle the request. For that you need to disable the CSRF protection:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => '...',
'csrf_protection' => false
));
}
Now your symfony Form can receive data from a custom Angular request.
All the things aside, I am still not sure about one thing, whether to display your form using Symfony or AngularJS.
Hope this helps.