There are already a number of ways to read local data through angular. In the previous example, most of the time the data was stored in the $scope variable of the module or directly using the Ng-init to define the initialized data. However, these methods are intended only to demonstrate the effectiveness of other functions. This time to learn how to combine angular and PHP to read data from the background .
First, using PHP, we define a set of background data, the following code (test.php):
<?php
Header ("Access-control-allow-origin: *");
Header ("Content-type:application/json; Charset=utf-8 ");
$conn = new Mysqli ("MyServer", "MyUser", "MyPassword", "Northwind");
$result = $conn->query ("Select CompanyName, City, Country from Customers");
$OUTP = "";
while ($rs = $result->fetch_array (MYSQLI_ASSOC)) {
if ($outp!= "") {$outp. = ",";}
$outp. = ' {' Name ': '. $rs ["CompanyName"]. '",';
$outp. = ' City ': ' . $rs ["City"] . '",';
$outp. = ' Country ': "'. $rs ["Country"] . '"}';
}
$OUTP = ' {Records ': ['. $outp. ']} ';
$conn->close ();
Echo ($OUTP);
? >
This code is relatively simple, after connecting to the database, use SQL statements from the database to select the appropriate data ($conn->query ("Select CompanyName, City,country from Customers"). After that, the extracted data is stored in the form of a key-value pair in the $OUTP variable, using the loop structure.
Next, in the JS operation is as follows:
<div ng-app= "myApp" ng-controller= "Customersctrl" >
<table>
<tr ng-repeat= "x in Names" >
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>
</div>
<script>
var app = Angular.module (' myApp ', []);
App.controller (' Customersctrl ', function ($scope, $http) {
$http. Get ("test.php")
. Success (Function ( Response) {$scope. names = Response.records;
}); </script>
The $http service is still used to read data, pass the URL path of the data file, return the data after success, and bind to the $scope.names variable.
The above is the entire content of this article, I hope to help you learn.