I'm learning AngularJS and wondered how I could get the PHP database results into an angular model. What I have:
<!DOCTYPE html>
<html data-ng-app="statsApp">
<head>
<title>Student Stats</title>
<script src="angular.min.js"></script>
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap-theme.css" rel="stylesheet" />
<?PHP
// Include dbcreds.inc for db info.
include('dbcreds.inc');
if(isset($_GET['fname']) && $_GET['fname'] !== "")
{
$lname = $_GET['fname'] . "%";
$sql = $conn->prepare("select * from students where fname like ?");
$sql->execute(array($lname));
$res = $sql->fetchAll();
$rownum = 0;
echo "\n <SCRIPT>";
echo "\n var model = [";
foreach($res as $r)
{
$rownum++;
echo "\n ";
print_r(json_encode(array("ID" => intval($r['id']),"FNAME" => $r['fname'],"LNAME" => $r['lname'],"GPA" => doubleval($r['gpa']))));
// Add a comma, if it's not the last datarow.
if($rownum < count($res))
{
echo ",";
}
}
echo "\n ];";
echo "\n ";
echo "\n var statsApp = angular.module(\"statsApp\",[]);";
echo "\n ";
echo "\n statsApp.controller(\"statsAppCtrl\", function (\$scope) {";
echo "\n \$scope.stats = model;";
echo "\n });";
echo "\n </SCRIPT>\n ";
}
?>
</head>
<body data-ng-controller="statsAppCtrl">
<div class="page-header">
<h2>
<span class="label label-default">{{ stats.length }}</SPAN>
</h2>
</div>
<div class="panel">
<table class="table table-striped">
<thead>
<TR>
<TH>ID</TH>
<TH>First Name</TH>
<TH>Last Name</TH>
<TH>GPA</TH>
</TR>
</thead>
<tbody>
<tr data-ng-repeat="stats_item in stats | orderBy:'ID'">
<td>{{ stats_item.ID }}</td>
<td>{{ stats_item.FNAME }}</td>
<td>{{ stats_item.LNAME }}</td>
<td>{{ stats_item.GPA }}</td>
</tr>
</tbody>
</table>
</div>
</body>
</HTML>
It seems to work ok, but I'm questioning whether I'm on the right track with this method of doing things. Thanks.