What is the correct way to remove an element from an Angular JS object?

I have ng-repeatwith a function ng-clickinside:

<div ng-repeat="item in data.education_list">
   <a href="" ng-click="deleteEducation(item)">Delete</a>
</div>

I pass an object itemfrom ng-repeatto a function deleteEducationto remove an element from data.education_list.

This is how the function looks:

$scope.deleteEducation = function (item){
    $scope.data.education_list.splice($scope.data.education_list.indexOf(item), 1);
}

Thus, this method sometimes does not work correctly. When I have an element in ng-repeat, and after deleting, itemmy HTML template is updated and deletes the line with another element, not the one that I deleted.

What is the correct way to delete?

data.education_list- an array of objects, if do {{data.education_list}}:

[{"name":"Test1","time":"01 Hun 2004 - 12 Sun 2006","Idusereducation":"86","usereducationIdToUser":"702","type":"1"}]

The second problem: If I have an object of objects instead of an array with a key:

{"1" : {obj}, 2 : "obj"}

And if I try to remove an element from an object by key:

delete OBJ[1]; I get the same problem.

+4
3

- $index, , angular .

<div ng-repeat="item in data.education_list">
   <a href="" ng-click="data.education_list.slice($index,1)">Delete</a>
</div>

. . , , .

JS

this.removeItem = function(item) {
    var index = $scope.data.education_list.indexOf(item);
    if (index != -1) {
        $scope.data.education_list.splice(index, 1);
    }
  };

HTML

ng-click="myctrl.removeItem(item)"

.indexOf vs $

+3
<div ng-repeat="item in data.education_list track by $index">
   <a href="" ng-click="deleteEducation($index)">Delete</a>
</div>

$scope.deleteEducation = function (position){
    $scope.data.education_list.splice(position, 1);
}
+2

. , , , -.

, , indexOf , . - , ;

$scope.removeReport = function(report) {
    var index = $scope.contact.reports.map(function(r) { return r.id;}).indexOf(report.id);
        if (index >= 0) {
          $scope.contact.reports.splice(index, 1);
        }
}
0

Source: https://habr.com/ru/post/1608349/


All Articles