user2184718
user2184718

Reputation: 715

Iterating through array angular

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.

Upvotes: 0

Views: 231

Answers (2)

Ivan Chernykh
Ivan Chernykh

Reputation: 42166

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!

Upvotes: 1

a better oliver
a better oliver

Reputation: 26828

$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.

Upvotes: 2

Related Questions