我在优惠券项目上工作,我想显示给客户所有的优惠券,可购买。当我单击调用函数"getAllCoupons()“的按钮时,它会工作并以JSON格式返回结果,但是当我想使用ng-repeat将结果插入到表中时,它只在函数返回多个优惠券时才显示,如果只有一个优惠券,则ng-repeat不会显示任何内容。
这是我的控制器
angular.module('companyApp', []);
angular.module('companyApp').controller('companyController',
function($rootScope, $scope, $http) {
$scope.getAllCoupons = function() {
$http.get("rest/CompanyService/getAllCoupon").success(
function(response) {
$scope.allCoupons = response.coupon;
});这是我的HTML
<div ng-app="companyApp" ng-controller="companyController">
<button class="tablinks" ng-click="getAllCoupons()" id="getAll">Get all coupons</button>
<table align="center" class="table table-striped" style="width: 900px;">
<thead>
<tr>
<th> Id </th>
<th>Coupon Title</th>
<th>Amount</th>
<th>Start Date</th>
<th>End Date</th>
<th>Price</th>
<th>Message</th>
<th>Coupon Type</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in allCoupons">
<td>{{ x.id }}</td>
<td>{{ x.title }}</td>
<td>{{ x.amount }}</td>
<td>{{ x.startDate }}</td>
<td>{{ x.endDate }}</td>
<td>{{ x.price }}</td>
<td>{{ x.message }}</td>
<td>{{ x.type }}</td>
</tr>
</tbody>
</table>
</div>但是,如果我不使用ng-repeat来编写它,那么它就可以工作,并且可以在JSON中获得它:
<div ng-app="companyApp" ng-controller="companyController">
<button class="tablinks" ng-click="getAllCoupons()" id="getAll">Get all coupons</button>
{{ allCoupons }}
</div>单张代金券的响应为:
{"coupon":{"amount":"149","endDate":"04/12/2020","id":"6","message":"only big sizes","price":"79.9","startDate":"07/08/2014","title":"pajamas","type":"FASHION"}}多张优惠券的响应是:
{"coupon":[{"amount":"60","endDate":"05/09/2020","id":"5","message":"warranty for 1 year","price":"200.99","startDate":"20/02/2014","title":"sunglasses","type":"FASHION"},{"amount":"149","endDate":"04/12/2020","id":"6","message":"only big sizes","price":"79.9","startDate":"07/08/2014","title":"pajamas","type":"FASHION"}]} 感谢您的帮助:)
发布于 2017-05-27 01:00:21
您引用的是对象而不是数组,请检查docs是否在ngRepeat的参数中使用对象。
您将需要ng-repeat="(key, value) in allCoupons
尝尝这个
<tr ng-repeat="(key, value) in allCoupons">
<td>{{ value.id }}</td>
<td>{{ value.title }}</td>
<td>{{ value.amount }}</td>
<td>{{ value.startDate }}</td>
<td>{{ value.endDate }}</td>
<td>{{ value.price }}</td>
<td>{{ value.message }}</td>
<td>{{ value.type }}</td>
</tr>希望能有所帮助
发布于 2017-05-29 10:56:28
服务器对单个优惠券的响应与对多个优惠券的响应格式不同。你应该和你的服务器人员谈谈,让他们来解决这个问题。优惠券属性需要是优惠券数组,而不管是单个优惠券还是多个优惠券。如果没有优惠券,则优惠券变量可以是未定义的,也可以是空数组。如果服务器人员为您做了此更改,则您的UI代码应该可以按原样工作。
我知道,有时候很难让服务器人员及时响应您的请求,特别是当他们在不同的团队时。如果是这种情况,您可以在UI代码上添加一个小补丁,以使UI与现有服务一起工作,直到服务器人员提出修复方案。您必须像下面这样更改您的$http.get代码片段(还需要结合@Claies建议的.success到.then的更改):
$http.get('rest/CompanyService/getAllCoupon').then(
function(response) {
if(!response.coupon) {
// No Coupons
$scope.allCoupons = [];
} else if(response.coupon instanceof Array) {
// Multiple Coupons
$scope.allCoupons = response.coupon;
} else {
// Single Coupon
$scope.allCoupons = [response.coupon];
}
});注意:此修复只是一个临时解决方案。服务器代码最终还是要修复的。服务器完全没有理由以不同的格式发送响应。
https://stackoverflow.com/questions/44205639
复制相似问题