【发布时间】:2016-10-04 05:10:03
【问题描述】:
我正在开发一个使用 Laravel 作为后端 API 和 AngularJS 作为前端的 Web 应用程序。我已成功从 Laravel API 获取数据并通过 AngularJS ng-repeat 显示它。现在我想要一个显示在表格中的每条记录的删除按钮。当用户单击该删除按钮时,它应该删除单击的记录。
我做了以下尝试,效果很好。但是当我单击删除按钮时会出现问题,它会从数据库中删除记录但它没有刷新记录列表,而不是刷新它只是显示表的标题,仅此而已。当我从浏览器手动刷新它时,它会显示记录列表。我想在删除记录后自动加载列表。
控制台错误:控制台错误:删除 http://localhost/ngresulty/public/api/result/50?id=50 500(内部 服务器错误)
删除前(列表):
MainCtrl.js
$scope.deleteResult = function(id) {
$scope.loading = true;
Result.destroy(id)
.success(function(data) {
// if successful, we'll need to refresh the comment list
Result.get()
.success(function(data) {
$scope.students = data;
$scope.loading = false;
});
});
};
MyAppService.js
angular.module('myAppService', [])
.factory('Result', function($http) {
return {
get : function() {
return $http.get('api/result');
},
show : function(id) {
return $http.get('api/result/' + id);
},
save : function(resultData) {
return $http({
method: 'POST',
url: 'api/result',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
data: $.param(resultData)
});
},
destroy : function(id) {
return $http.delete('api/result/' + id,{params: {id}});
}
}
});
App.js
var myApp = angular.module('myApp', ['mainCtrl', 'myAppService']);
结果视图:
<table class="table table-striped">
<thead>
<tr>
<th>Roll No</th>
<th>Student Name</th>
<th>Father Name</th>
<th>Obtained Marks</th>
<th>Total Marks</th>
<th>Percentage</th>
<th>Delete</th>
</tr>
</thead>
<tbody ng-hide="loading" ng-repeat="student in students | filter:searchText">
<tr>
<td>@{{ student.rollno }}</td>
<td>@{{ student.name }}</td>
<td>@{{ student.fname }}</td>
<td>@{{ student.obtainedmarks }}</td>
<td>@{{ student.totalmarks }}</td>
<td>@{{ student.percentage }}</td>
<td>
<a href="#" ng-click="deleteResult(student.id)" class="text-muted btn-danger btn-lg">Delete</a></p>
</td>
</tr>
</tbody>
</table>
我试过但没用:
$scope.deleteResult = function(id) {
$scope.loading = true;
Result.destroy(id)
.success(function(data) {
// do something with data if you want to
$scope.students.splice(id, 1);
});
};
解决方案: 每当您收到 500 内部错误时,问题将来自服务器端。问题出在服务器端,我所做的只是将销毁服务更改为
destroy : function(id) {
return $http.delete('api/result/' + id);
}
在 laravel 控制器中,我返回了一个布尔值 true,但我将其更改为 ID
return \Response::json($studentid);
因为我需要那个 ID 才能成功返回,然后它就像一个魅力。
【问题讨论】:
标签: javascript angularjs laravel laravel-5