Share fun
Share fun

Reputation: 177

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>

Upvotes: 5

Views: 10274

Answers (3)

Prabhu Das
Prabhu Das

Reputation: 11

I had similar requirement, and the below worked for me.

data-ng-click="editField(product, '<?php echo $_SESSION["login_user"] ?>')"

Upvotes: 0

Munanshu Madaan
Munanshu Madaan

Reputation: 170

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)); ?>">

Upvotes: 5

Ali
Ali

Reputation: 3081

As discussed earlier, you need to format your data in the names's to;

  1. be a valid valid JSON
  2. provide a field name since you are seeking it in your loop (ng-repeat)

So at the moment the value assigned to your "names" is "eden frank matt" as you mentioned in your comment. this needs to be changed to something like:

[
    {name: 'eden'},
    {frank: 'eden'},
    {matt: 'eden'}
]

so when you check the html source we should have a collection of lets say "people" and then going through all of its element and point to their field "name" :

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


<body ng-app>

<ul ng-init="people = [{name:'eden'}, {name:'frank'}, {name:'matt'}]">
    <li ng-repeat="person in people">
        <p>{{person.name}}</p>
    </li>
</ul>

</body>
</html>

Upvotes: 1

Related Questions