我试图以json格式从服务器(servlet)获取数据并添加到表中.数据从服务器端成功获取,当我使用console.log(数据)时,它会打印数据,但不会将其添加到表中.
module.js:
var module = angular.module('myApp', []);
module.service('ContactService', function($http) {
var contacts = [{ }];
this.getContacts = function($http) {
var response = $http.get("/PersonalDetail/AngularServlet");
response.success(function(data, status, header, config) {
contacts=data;
console.log("contacts: " + contacts);
return contacts;
});
response.error(function(data, status, header, config) {
return null
});
return contacts;
}
this.list = function($http) {
return this.getContacts($http);
}
});
controller.js
module.controller("ContactController", function($scope,$http,ContactService) {
$scope.contacts=ContactService.list($http);
}
的index.html
<html data-ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!--<title>JSP Page</title>-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js" type="text/javascript"></script>
<script src="js/module/module.js" type="text/javascript" ></script>
<script src="js/controller/controller.js" type="text/javascript" ></script>
</head>
<body>
<div data-ng-controller="ContactController">
<table class="table table-striped table-bordered" bgcolor="orange" border="1">
<thead>
<tr>
<th>Name </th>
<th>Email </th>
<th>Phone </th>
<th>Action </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in contacts">
<td>{{ contact.name}}</td>
<td>{{ contact.email}}</td>
<td>{{ contact.phone}}</td>
</tr>
</tbody>
</table>
</div>
</body>
最佳答案 这是处理Angular中的promise的正确方法.在控制器中:
module.controller("ContactController", function($scope, $http, ContactService) {
ContactService.list().then(function(data) {
$scope.contacts = data;
});
}
然后修改服务:
module.service('ContactService', function ($http) {
this.getContacts = function () {
return $http.get("/PersonalDetail/AngularServlet").then(function (data, status, header, config) {
return contacts;
}, function (data, status, header, config) {
return null;
});
}
this.list = function () {
return this.getContacts();
}
});
那么最重要的是你应该从list方法(和getContacts)返回promise对象.