There have been many methods to read local data through angular. In the previous examples, in most cases, the data is stored in the $scope variable of the module, or the initialized data is directly defined using ng-init. But these methods are only for demonstrating the effects of other functions. This time let’s learn how to combine Angular and PHP to read data from the background.
First, using PHP, we defined a set of background data, the code is as follows (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); ?>
<div ng-app="myApp" ng-c <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 above introduces the use of Angularjs to read background data from PHP, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.