Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass php variable/array data to angular js

I am using php database connectivity with "$row" as an array that stores name as a field in it .But after lots of searching i dint get how to pass php variable in angular js here's the code ,I am trying to achieve.how is it possible i am new to this your help will be appreciated.

<?php

$con = mysqli_connect('localhost','root','','practice');

if (!$con) {
    die("couldnt connect". mysqli_error);
}

$q= "select * from test";
$result= $con->query($q);

if ($result->num_rows>0) {

    while ($row = $result->fetch_assoc()) {

        echo $row['name']."<br>";

    }
}

print_r($result);

echo json_encode($result);

?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js">
</head>
<body>

<ul ng-init="names = <?php echo htmlspecialchars(json_encode($row)); ?>">
<li ng-repeat="x in names">
   <p>{{x.name}}</p>
</li>
</ul>
</body>
</html>
like image 749
Share fun Avatar asked Jul 05 '15 08:07

Share fun


1 Answers

Your php code needs a bit of improvement use this instead of that:

$arr = array();
if ($result->num_rows>0) {

while ($row = $result->fetch_assoc()) {

$arr[] = $row['name'] ;

}
}

Then echo it as

<ul ng-init="names = <?php echo htmlspecialchars(json_encode($arr)); ?>">
like image 164
Munanshu Madaan Avatar answered Oct 08 '22 16:10

Munanshu Madaan