I'm using Symfony2 with Twig and AngularJS. I need to pass Twig variable to angular's function. Currently I tried doing that like this: ng-click="submitPost({{ channelName }})" but when I console.log to check that variable I see it as undefined. How do I pass Twig variables to angular functions?
2 Answers
If you are using Twig with AngularJS you will most likly run into conflicts as you might know. One solution is to use Angulars $interpolateProvider to change the start and end interpolation tags like so:
angular.module('myApp', []).config(function($interpolateProvider){
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
});
In this case Angular will use {[{ and }]} to interpolate expressions. It might be a bit odd to type but you can chose whatever you like. However, this will solve the conflicts between Twig and Angular.
Comments
Use temporary javascript variable to store the twig variable
var tmp = "{{ channelName }}";
ng-click="submitPost(tmp)"
2 Comments
LordTribual
In my opinion not really clean. If you need to pass many of those twig variables you have a bunch of temporary variables. In contrast of course a redefinition of the
$interpolateProvider can be overhead if you only need to pass a few twig variables.Med
Using temporary vars is a quick fix, but you can still write something like
ng-click='submitPost("{{ channelName }}")' ( please notice the quotes and double quotes )
ng-click="submitPost(channelName )"