2

Some context: I have a task list using an api to save each task to mysql. My delete method is triggered by a button with ng-click (ng-click="remove(todo, $index)") and looks like this:

  $scope.remove = function (todo, index) {
    $http({
      method: 'DELETE',
      url: 'http://api.dev/api/task/delete/' + todo.id }).then(function (response) {
        $scope.todos.splice(index, 1);
      });
  };

This works just fine, but I'm wondering how could I make it work without passing the todo and using only the index?

3
  • I believe you need to have the id of the todo to know which todo to delete. Commented Oct 3, 2017 at 14:38
  • What is the reason for not passing the todo? Commented Oct 3, 2017 at 14:38
  • @Matt mostly just for fun, but can't I get to the id using the index? Commented Oct 3, 2017 at 14:45

1 Answer 1

2

By using the same array you fill the list from - todos. Assuming you have not manipulated the order of items in the list by applying filters or using order by when creating the list.

    $scope.remove = function (index) {
    var listElement = $scope.todos[index];
    $http({
      method: 'DELETE',
      url: 'http://api.dev/api/task/delete/' + listElement .id }).then(function (response) {
        $scope.todos.splice(index, 1);
      });
  };

Do note, this is not best practice due to the fact you sometimes mess with the order of the list.

Here Is a little demo, demonstrating what I am talking about. Look the list order in the controller. Now, look at indexes after the names in HTML.

demo

Sign up to request clarification or add additional context in comments.

5 Comments

I believe this will give an error since todos it's not defined
Right you could do it this way. You could get todos by doing angular.element('#todos') and tag todos with said id. Buuuuuuut, please don't. This is bad.
You are right, when I copied I cut out the $scope part.
Like @DanteTheSmith said. This is not guaranteed to be correct.
It does work, thank you DanteTheSmith and @Matt, but you make good points and I'll probably hold to my initial solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.