Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AngularJS Basics (1.x) Improving Our Todo App Using Filters to Order ng-repeat Items

robertgruner
robertgruner
11,850 Points

Ordering mechanism interferes with deletion method

The ordering by completed todos introduces a bug in the deletion function since the SPLICE method is used to cut down the array. Try it out:

  • mark a todo as completed
  • try to delete this exact completed todo
  • see that it deletes another (random?) todo

This happens because the given $index is not the persistent identifier of the todo in the todos array.

Not cutting down the array but rather FILTERing it solves the problem imho. I improved the deletion function as follows:

   $scope.deleteItem = function(todo) {

        //Used $$hashKey because it is the unique and persistent identifier for the item of the array
       $scope.todos = $filter('filter')($scope.todos, function(value, index) {

             //Everything what is returned stays in the filtered array
             return value.$$hashKey !== todo.$$hashKey;
        });

     $todoService.deleteItem(todo);
   };
Gennady Kravchenko
Gennady Kravchenko
897 Points

I've also noticed this behavior at marked as completed todos. I didn't try this approach, but it seems to me somehow pretty specific. Is there a common way or best practices and recommendations on performing the "add" and "delete" operations in the list (JSON array) which would consider diverse sorting and filtering?

1 Answer

Patrick O'Dacre
Patrick O'Dacre
15,471 Points

I hope this helps.

In the todoCtrl use the following:

 $scope.deleteTodo = function (todo) {
     // Before deleting, get the index of the todo associated with the delete button that has been clicked.
     $scope.todos.splice($scope.todos.indexOf(todo), 1);
      dataService.deleteTodo(todo);
    };

The delete issue is seen in the MEAN stack course, too.