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 Finalizing Our Application

Issues with deleting checked-off items

Has anyone else been having issues with deleting completed items? I've been observing strange behavior after checking a todo as completed and then trying to delete that todo. Sometimes it deletes the todo above it, sometimes it deletes the one after it, or sometimes it deletes the correct item. I'm not sure why this is happening. Any suggestions?

Thomas Nilsen
Thomas Nilsen
14,957 Points

That's difficult to say without having a look at your code

3 Answers

Daniel Li
Daniel Li
15,244 Points

The problem lies with this piece of code that was added some lessons ago.

$scope.deleteTodo = function(todo, $index) {
    dataService.deleteTodo(todo);
    $scope.todos.splice($index, 1);
};

$index is dynamic, so when a completed todo is moved to the bottom of the list its value changes. Splicing was done on the todos array in $scope which the index never changes.

This is my fix

$scope.deleteTodo = function(todo, $index) {
  dataService.deleteTodo(todo);
  $scope.todos = $scope.todos.filter(function(val) {
    return !(val.name === todo.name);
  });
};

I've filter away the todo object in $scope.todos that matches the name value on the given todo, not the most elegant perhaps.

Marina Kazakova
Marina Kazakova
5,765 Points

I noticed this too. How would you suggest to fix this?

Daniel Li
Daniel Li
15,244 Points

Updated my answer, hope it helps! :)