【发布时间】:2015-07-09 15:29:02
【问题描述】:
我有一个 api 调用给我数据列表,我正在通过 ng-repeat 迭代数据(它是一个超过 100 项的列表)
为了获取数据列表,我在 angularjs 中调用了 App Controller 中的 Api,如下所示:
var path = serverUrl + 'api/getAllMails';
$http.get(path).then(function (result) {
$scope.mails=result
})
为了迭代 Html 文件中的邮件,我使用了如下表
<table>
<tr class="header">
<th class="center">Id</th>
<th class="center">Mode of Payment</th>
<th class="center">Payment Collected</th>
<th class="center">Status</th>
</tr>
<tr ng-repeat="mail in mails">
<td>{{mail.id}}</td>
<td>{{mail.paymentType}}</td>
<td>Rs. {{mail.cost}}
<input type="text" ng-model="mail.cost">
<button ng-click="updateCost=(mail.id, mail.cost)">Update Cost</button>
</td>
<td>{{mail.status}}
<input type="text" ng-model="mail.status">
<button ng-click="updateStatus(mail.id, mail.status)">Update Status</button>
</td>
</tr>
</table>
假设在第一次迭代中,成本为“100”,状态为“待定”。我只需要更新这一行,将成本更改为“1000”,状态将是“已交付”。
在我的 Angularjs 应用控制器中,我创建了方法。这两个方法是调用api和更新数据库中的数据并返回更新的邮件列表。
$scope.updateStatus = function(mailId, mailStatus) {
var path = serverUrl + 'api/updateStatus';
$http.get(path, {
params: {
mailId: mailId,
mailStatus: mailStatus
}
}).then(function(result) {
$scope.mails = result
})
}
$scope.updateCost = function(mailId, mailCost) {
var path = serverUrl + 'api/updateStatus';
$http.get(path, {
params: {
mailId: mailId,
mailCost: mailCost
}
}).then(function(result) {
$scope.mails = result
})
}
这些代码运行良好,但加载页面需要花费大量时间。那么我可以做些什么来减少加载时间,或者有没有更好的方法来做同样的事情。
任何帮助都将不胜感激。谢谢
【问题讨论】:
-
什么需要很长时间? API 调用(待处理)还是 ng-repeat?
-
在您的 ng-repeat 中添加
track by $index或track by mailId,可能差别不大,但会有所帮助。 -
猜测 api 调用需要很长时间。您可以从前端部分做的最大事情是您可以通过单击某些按钮或其他方式进行调用或添加加载程序。这样用户体验会好很多。
-
API 调用需要 4.5 秒,但 ng-repeat 需要更多时间。
-
所以你的 api 在每次更新后都会从你的数据库中返回完整的集合?你能不能只返回更新的行并用更新的对象替换前端模型中的相关对象?
标签: javascript angularjs