我是AngularJS的新手。
我有一个带有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-route工作是因为你正在加载&#34; myApp&#34;在第一个实例上,然后使用你的ng-view加载可以工作的HTML页面,但由于你的模块没有作为依赖项添加到你的控制器上,它不会加载控制器,因为它正在寻找显式用于使用&#34; myApp&#34;的控制器,它通过直接路由加载,因为你从未告诉它明确使用&#34; myApp&#34;。
你的href标签也需要#/ list。
您还需要为index.html引用一次角度脚本,因为它适用于整个应用程序,因为当您加载&#34; myList.htm&#34;您将在ng-view标记中加载这些脚本的副本。如果&#34; main.htm&#34;首先加载而不是默认的&#34; index.html&#34;,即使直接转到localhost:portnum /#/ list,你的路由也能正常工作。
此外,您应该在&#34; main.htm&#34;上引用您的控制器脚本,这可以确保它们被加载以在ng-view中使用,对于较大的页面,您可以在页面底部如;
<script src="scripts/app.js"></script>
<script src="scripts/controller"><script>
文件路径与当前项目目录相关。
希望它有所帮助!