我正在處理優惠券項目,並且我想向客戶顯示可供購買的所有優惠券。 當我點擊調用函數「getAllCoupons()」的按鈕時,它可以工作,並以JSON的形式返回結果,但是當我想用ng-將重複結果插入表格時,它只會在函數返回更多時顯示如果只有一張優惠券,則ng-repeat不會顯示任何內容。ng-repeat僅在DB返回多於一個結果時才顯示
這是我的控制器
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-重複它的工作原理,我得到它在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"}]}
感謝您的幫助:)
您可以用一張優惠券和另一張優惠券發佈樣品響應對象嗎?我猜測,當只有一張優惠券時,服務器會向您發送單一優惠券實例,而不是帶有單個優惠券元素的數組。 – CodeWarrior
在這兩種情況下,我都會獲得優惠券的詳細信息作爲回覆,但不會顯示給客戶,我根本沒有得到任何錯誤。@CodeWarrior –
你的UI代碼似乎沒問題。服務器響應的格式可能是罪魁禍首。這就是爲什麼我們需要查看單個優惠券和多個優惠券的服務器響應。 – CodeWarrior