简体   繁体   English

如何在AngularJS中删除后自动加载/刷新视图数据?

[英]How to automatically load/refresh view data after delete in AngularJS?

I am working on a Web Application using Laravel as backend API and AngularJS for frontend. 我正在使用Laravel作为后端API和AngularJS用于前端的Web应用程序。 I have successfully fetched the data from Laravel API and displayed it via AngularJS ng-repeat. 我已成功从Laravel API获取数据并通过AngularJS ng-repeat显示它。 Now i want a delete button for each record which is displayed in the table. 现在我想要一个显示在表中的每条记录的删除按钮。 When a user click that delete button it should delete the clicked record. 当用户单击该删除按钮时,它应删除所单击的记录。

I did the following try which is working perfectly.But the problem occurs when i click delete button it deletes record from database but it is not refreshing the records list , instead of refreshing it just shows the headers titles of table and nothing else. 我做了以下尝试,这是完美的工作。但是,当我点击删除按钮它删除记录从数据库, 但它没有刷新记录列表 ,而不是刷新它只是显示表的标题标题,没有别的问题。 When i manually refresh it from browser then it displays back the records list. 当我从浏览器手动刷新它然后它显示回记录列表。 I want to load the list automatically after the record is deleted. 我想在删除记录后自动加载列表。

Console Error : Console Error: DELETE http://localhost/ngresulty/public/api/result/50?id=50 500 (Internal Server Error) 控制台错误:控制台错误:DELETE http:// localhost / ngresulty / public / api / result / 50?id = 50 500(内部服务器错误)

Before Delete ( List ): 删除前(列表):

所有记录列表 After delete Scene: 删除场景后:

当我按下删除时,记录将从数据库中删除,但列表如下所示

MainCtrl.js 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 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 App.js

var myApp = angular.module('myApp', ['mainCtrl', 'myAppService']);

Results View : 结果查看:

<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>

What I tried but not working : 我尝试过但没有工作:

 $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);

            });
    };

Solution : Whenever you get 500 internal error the issue will be from server side. 解决方案:每当您收到500内部错误时,问题将来自服务器端。 The issue was with server side all i did was change my destroy service to 问题在于服务器端,我所做的就是将我的销毁服务更改为

 destroy : function(id) {
                return $http.delete('api/result/' + id);
} 

and in laravel controller i was returning a bool value true but i changed that to ID 并且在laravel控制器中我返回一个bool值为true但我将其更改为ID

return \\Response::json($studentid);

because i was in need of that ID for success return and then it worked like a charm. 因为我需要那个ID来获得成功,然后它就像一个魅力。

The problem is Array splice method takes the index of array as first argument and you are providing it Student Id which is not a array index. 问题是Array splice方法将数组的索引作为第一个参数,并且您提供的是Student Id,它不是数组索引。 You have to find the index of student id in the array then pass it into the splice method 您必须在数组中找到student id的索引,然后将其传递给splice方法

$scope.findWithAttr= function(array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
    if(array[i][attr] === value) {
        return i;
    }
} }

Now you can call this function is destroy success block. 现在你可以调用这个函数来破坏成功块。

$scope.deleteResult = function(idToDelete) {
    $scope.loading = true; 

    $http.delete('api/result/' + id,{params: {id}}); }
        .then(function(data) {

            var index=$scope.findWithAttr($scope.students,id,idToDelete);
            $scope.students.splice(index, 1);

        });
};

You are splicing the data incorrectly. 您正在错误地拼接数据。

Do like this to splice the data in destroy success block. 这样做是为了在destroy success块中拼接数据。

var del_index = $scope.students.findIndex(function(d){return d.id == id});
if(del_index>0)//if index of the id to be removed found
  $scope.students.splice(del_index, 1);

There is a javascript library called lodash 有一个名为lodash的javascript库

This library provides the remove function where you can remove an element from the data. 此库提供remove函数 ,您可以从中删除数据中的元素。

Sometimes slice does not work. 有时切片不起作用。 SO try this hopefully it would work. 所以希望这会有用。

 $scope.deleteResult = function(id) {
    $scope.loading = true; 

    Result.destroy(id)
        .success(function(data) {

            // do something with data if you want to
            _.remove($scope.students,function(student){
             return id==studednt.id; 
             }

        });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM