大家好,我是angular js的新手,我写了以下页面,该页面似乎要显示一个员工详细信息表,该表来自“ http://localhost:8080/SpringRestHibernateWebTest/employee/listEmployee”作为json对象。
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>SPRING REST HIBERNATE WEB TEST</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.js"></script>
<script type="text/javascript">
var app = angular
.module("myModule",[])
.controller("myController", function($scope){
var EmployeeJSON = null;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:8080/SpringRestHibernateWebTest/employee/listEmployee", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send();
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
var response = JSON.stringify(xhttp.responseText);
//alert(JSON.parse(response));
EmployeeJSON = JSON.parse(response);
var employees = EmployeeJSON;
$scope.employees = employees;
$scope.IsVisible = true;
alert('employees '+employees);
alert('$scope.employees '+$scope.employees);
alert('EmployeeJSON '+EmployeeJSON);
}
}
});
<body ng-app="myModule">
<h1>SPRING REST HIBERNATE WEB TEST</h1>
<a href="/SpringRestHibernateWebTest/employee/listEmployee">CLICK FOR EMPLOYEE LIST</a>
<form>
<table>
<tr> <td>EMPLOYEE ID</td> <td><input type="text" id="emp_id"></td> </tr>
<tr> <td>EMPLOYEE NAME</td> <td><input type="text" id="emp_name"></td> </tr>
<tr> <td>EMPLOYEE SALARY</td> <td><input type="text" id="emp_salary"></td> </tr>
<tr> <td>EMPLOYEE ADDRESS</td> <td><input type="text" id="emp_address"></td> </tr>
</table>
</form>
<div ng-controller="myController">
<table>
<thead>
<tr> <td>EMPLOYEE ID</td> <td>EMPLOYEE NAME</td> <td>EMPLOYEE SALARY</td><td>EMPLOYEE ADDRESS</td></tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees">
<td>{{employee.employeeId}}</td>
<td>{{employee.employeeName}}</td>
<td>{{employee.employeeSalary}}</td>
<td>{{employee.employeeAddress}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
根据编码,在页面加载时,来自角度控制器的警报被填充并显示json对象,但表未被填充。
任何建议将不胜感激!
答案 0 :(得分:2)
您使用mon
,它位于Angular之外。
因此,您必须使用XMLHttpRequest
手动触发Angular的摘要周期。
$scope.$apply();
不过,执行对API的http请求的更好方法是使用// ...
$scope.employees = employees;
$scope.IsVisible = true;
$scope.$apply();
// ...
服务。
首先,您必须在Controller定义中注入$http
服务:
$http
然后,您可以看到类似的内容:
.controller("myController", function($scope, $http) {
通过这种方式,您不必手动致电var endpoint = "http://localhost:8080/SpringRestHibernateWebTest/employee/listEmployee";
return $http.get(endpoint)
.then(function(response) {
// Use data as per your needs
// response.data
})
.catch(function(response) {
// Error occured
})
.finally(function() {
// Always do something
});
。
$scope.$apply();
服务中的更多信息,您可以在w3schools或Angular documentation或网络上的许多地方找到。