0

I am following a todo list angular tutorial. Right now, I would like to loop through all of my todo list and clear all of the items where the attribute done is true.

Right now in my index.html file I have a button with the ng-click attribute of "clearCompleted()". That function looks like this in my js file:

$scope.clearCompleted = function () {
  $scope.todos = $filter($scope.todos, function(todo){
    return !todo.done;
  });
};

What is wrong with this function because it is not clearing the todo items that are being set to done:true.

And in more of a general question, what is the typical way I could say something along the lines of "select all the items where the attribute done is true" because I am more used to ruby and not javascript.

3
  • I understand that, clearly something in this function is not letting me filter properly. Commented Jan 2, 2014 at 17:12
  • Ahh - I misread your code. No, that does appear to be the right idea. Sorry, if I were an Angular guy I could likely help. Commented Jan 2, 2014 at 17:14
  • Why use $filter at all? Seems like just using Array.filter (or equivalent helper with jQuery or underscore) would be simpler and probably faster. Commented Jan 2, 2014 at 21:30

2 Answers 2

2

$filter(name)gets the filter with that name. In order to actually call it you can write `$filter(name)(/arguments for the filter/)

There is a predefined filter called filter that can be used for filtering arrays. You pass in an object for comparisons:

$scope.clearCompleted = function () {
    $scope.todos = $filter("filter")($scope.todos, {done:false});
};

Which returns all items that have the property donewith the value false.

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

Comments

1

Try this syntax:

$scope.todos = $filter("filter")($scope.todos, function(todo){

Example: http://jsfiddle.net/cherniv/89Qqs/

And don't forget to inject the $filter service into controller first!

Comments

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.