2016-11-07 23 views
0

我是AngularJS的新手。AngularJS - HTML页面在使用ngView时不显示返回的数据

我有一个SQL数据库PHP服务器,我有AngularJS一个HTML页面和发送$ HTTP GET请求到服务器,返回数据的数组显示在一个表上相同的按钮页。

每当我直接打开页面websitename/myList.htm和我按下getList,数据显示完美没有任何问题,但一旦我通过路由,ngView打开页面,页面元素出现,但如果我按下按钮,页面不会从服务器获取数据更新。

这两个页面之间是否需要额外的数据链接?

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> 

谢谢。

+0

给我们看一些代码 –

回答

0

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

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

你没有通过NG-路线工作的原因是因为你装“对myApp”的第一个实例,然后使用您的NG-视图加载HTML网页,其中会的工作,而是因为你的模块没有作为依赖添加到你的控制器上,它不会加载控制器,因为它明确寻找使用“myApp”的控制器,它通过直接路由加载,因为你从未告诉它明确使用“myApp”。

您还需要#/列表您的href标记。

您还只需要为您的index.html引用一次角码脚本,因为它与整个应用程序有关,因为当您加载“myList.htm”时,您将在ng中加载这些脚本的副本 - 查看标签。如果“main.htm”首先被加载而不是默认的“index.html”,那么这个方法可以工作,即使直接进入localhost:portnum /#/ list,你的路由也可以正常工作。

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

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

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

希望它有帮助!

相关问题