首页 > 解决方案 > AngularJS控制器未在路由视图中显示数据库中的数据

问题描述

我是 AngularJS 的新手,我正试图让我的一个路由页面从 MySQL 数据库加载数据。在网上看了几个不同的教程后,我似乎做错了什么,无法弄清楚为什么它不起作用。

索引页:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <base href="/angtest/">
        <title>AngularJS Test</title>
    </head>
    <body ng-app="myApp">
        <p>
            <a href="home">Home</a> - <a href="about">About</a> - <a href="items">Items</a>
            <br>
            Click on the links to go to new pages.
        </p>
        <div ng-view></div>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.7/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.7/angular-route.js"></script>
        <script>
            var app = angular.module("myApp", ["ngRoute"]);
            app.config(['$routeProvider','$locationProvider',
            function($routeProvider, $locationProvider) {
            $locationProvider.html5Mode(true);
            $routeProvider
                .when("/", {
                    templateUrl : "home.html"
                }).when("/home", {
                    redirectTo : "/"
                }).when("/about", {
                    templateUrl : "about.html"
                }).when("/items", {
                    templateUrl : "items.html",
                    controller : "usercontroller"
                }).otherwise({
                    redirectTo : "/"
                });
            }]);
            app.controller("usercontroller", function($scope, $http){
                $http.get("select.php")
                .then(function(data){
                    $scope.items = data;
                });
            });
        </script>
    </body>
</html>

当转到 /home、/about 或 /items 时,页面加载正确,但 /items 没有获取数据库信息。

标题和描述是我想显示的项目表中的列。

项目页面:

<h1>MySQL Database</h1>
<div ng-controller="usercontroller">
    <table>
        <tr>
            <th>Item Name</th>
            <th>Item Description</th>
        </tr>
        <tr ng-repeat="x in items">
            <td>{{ x.title }}</td>
            <td>{{ x.description }}</td>
        </tr>
    </table>
</div>

选择脚本:

<?php
    $connect = mysqli_connect("localhost", "USERNAME", "PASSWORD", "DBNAME");
    $output = array();
    $query = "SELECT * FROM items";
    $result = mysqli_query($connect, $query);
    if(mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_array($result)) {
            $output[] = $row;
        }
        echo json_encode($output);
    }
?>

在控制台窗口中,不显示任何错误。

更新

为了检查控制台窗口,我将控制器更改为:

app.controller("usercontroller", function($scope, $http){
    $http.get("select.php")
    .then(function(data){
        console.log(data);
        $scope.items = data;
    });
});

日志显示:

控制台窗口

标签: phpangularjs

解决方案


项目页面

<h1>MySQL Database</h1> <div> <table> <tr> <th>Item Name</th> <th>Item Description</th> </tr> <tr ng-repeat="x in items"> <td>{{ x.title }}</td> <td>{{ x.description }}</td> </tr> </table> </div>

推荐阅读