0

I want to load my initial page with php, so instead of making rest call to get variable, I already have the variable in my page , I need it to some way assign it to angular. I saw different ways for doing it like

<.....ng-init="somefunction('<?echo $myjsonstring?>')"> 

but this is not working as it thinks that my json string ends at the first double codes .I though to replace double codes with some special symbol and in angular to replace it back but this require some processing which I think will reduce its performance. Is there any other way to do this?

  • Usually data from php aimed to be used by js are stored as as an encoded string into a data attribute and decoded by the js. See an example here http://stackoverflow.com/questions/7322682/best-way-to-store-json-in-an-html-attribute – maalls Apr 25 '15 at 06:19

2 Answers2

0

Try json_encode:

<...ng-init="somefunction('<?php echo json_encode($myjsonstring); ?>')">
sfletche
  • 47,248
  • 30
  • 103
  • 119
  • this did not work as if encoded json string is something like {"key:"value"},then it gets converted into <...ng-init="somefunction('{"key:"value"}')"> , here it assumes that the parameter in the function as only "{" , and I am getting parse error. – abhi nand Apr 25 '15 at 06:58
0

If you want to build a 'complicated' JSON, You can use the Simple JSON for PHP like this :

<...ng-init="somefunction('<?php
include('includes/json.php');
$Json = new json();
$Json->add("teachers", $teachers_object);
$Json->add("users", $users_object);
$Json->add("someArray",$anArray);
echo $Json->make();
?>')">
Alexis Paques
  • 1,885
  • 15
  • 29