AngularJS - HTML 使用 ngView 时页面不显示返回的数据

AngularJS - HTML page does not show returned data when using ngView

我是 AngularJS 的新手。

我有一个带有 sql 数据库的 php 服务器,我有一个带有 AngularJS 的 html 页面和一个向服务器,其中 returns 显示在同一页面上的 table 中的数据数组。

每当我直接打开页面 websitename/myList.htm 并按下 getList 时,数据会完美显示,没有任何问题,但是一旦我通过路由、ngView 打开页面,页面元素就会出现,但是如果我按下按钮,页面没有使用来自服务器的数据进行更新。

两页之间是否需要额外的数据link?

myList.htm

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>

<script>
angular.module("crudApp", [])
.controller("userController", function($scope,$http){
$scope.users = [];
$scope.tempUserData = {};
// function to get records from the database

$scope.getList = function(){
$http.get('action.php', {
params:{
'type':'getList'
        }
    }).success(function(response){
        if(response.status == 'OK'){
            $scope.users = response.records;
        }
    });
};


});

</script>


<body ng-app="crudApp">
<div class="container" ng-controller="userController">

<a href="javascript:void(0);" class="btn btn-success"     ng-click="getList()">getList</a>


        <table class="table table-striped">
            <tr>
                <th width="20%">Name</th>
                <th width="30%">Email</th>
                <th width="20%">Phone</th>
            </tr>
            <tr ng-repeat="user in users">
                <td>{{user.Name}}</td>
                <td>{{user.Email}}</td>
                <td>{{user.Phone}}</td>
            </tr>
        </table>

<p>end of table</p>
</body>

</html>

包含路线的页面:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>

<body ng-app="myApp">

<p><a href="#/">Main</a></p>
<a href="#list">List</a>



<div ng-view></div>

<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
    templateUrl : "main.htm"
})
.when("/list", {
    templateUrl : "myList.htm"
});
});
</script>

<p>Click on the links to navigate</p>
</body>
</html>

谢谢。

您的控制器和 app.js 需要相同的 .module 名称,例如;

var app = angular.module("myApp", ["ngRoute"]);
angular.module("myApp", []).controller("userController"

你的无法通过 ng-route 工作的原因是因为你在第一个实例中加载 "myApp",然后使用你的 ng-view 加载可以工作的 HTML 页面,但是因为你的模块没有作为依赖项添加到你的控制器上,它不会加载控制器,因为它正在明确寻找使用 "myApp" 的控制器,它通过直接路由加载,因为你从未明确告诉它使用 "myApp".

您的 href 标签还需要#/list。

你也只需要为你的 index.html 引用你的 angular 脚本一次,因为它适用于整个应用程序,因为当你加载 "myList.htm" 你会加载一个ng-view 标签中这些脚本的副本。如果首先加载 "main.htm" 而不是默认的 "index.html",则此方法有效,即使直接转到 localhost:portnum/#/list.

,您的路由也能正常工作

此外,您应该在 "main.htm" 上引用您的控制器脚本,这确保它们被加载以在 ng-view 中使用,对于较大的页面,您可以在页面底部引用脚本,例如作为;

<script src="scripts/app.js"></script>
<script src="scripts/controller"><script>

文件路径与当前项目目录相关。

希望对您有所帮助!