初学AngularJS
我有一个php服务器与sql数据库,我有一个html页面与AngularJS和一个按钮,发送$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>
谢谢。
控制器和app.js需要使用相同的.module名,比如;
var app = angular.module("myApp", ["ngRoute"]);
angular.module("myApp", []).controller("userController"
你的没有通过ng-route工作的原因是因为你在第一个实例上加载了"myApp",然后使用你的ng-view加载了可以工作的HTML页面,但是因为你的模块没有作为一个依赖项添加到你的控制器上,它不会加载控制器,因为它正在显式地寻找使用"myApp"的控制器,它通过直接路由加载,因为你从来没有告诉它显式地使用"myApp"。
你还需要#/list作为你的href标签。
你也只需要在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>
文件路径与当前项目目录相关。
希望有帮助!