spuder
spuder

Reputation: 18387

How to create a filter in AngularJS

Using AngularJS, how do you create a subset of items in an array?

For example; create a new array from "todos" that only includes the "done:true" items.

function fooController ($scope) {

$scope.todos = [
        {text:'foo'        , done:false}, 
        {text:'foobar'     , done:true},
        {text:'foofoo'     , done:false}, 
        {text:'foobar2'    , done:true}
 ]

}

http://docs.angularjs.org/api/ng.filter:filter

http://www.youtube.com/watch?v=WuiHuZq_cg4&list=PL173F1A311439C05D&context=C48ac877ADvjVQa1PpcFONnl4Q5x8hqvT6tRBTE-m0-Ym47jO3PEE%3D

See about 10:45 -> end

Upvotes: 2

Views: 2377

Answers (2)

Tim Withers
Tim Withers

Reputation: 12059

Just add the filter to your ngRepeat and only show what you want:

ng-repeat='todo in todos | filter:done==true'

Fiddle: http://jsfiddle.net/dPWsv/1/

If you want to completely REMOVE the element from the list, utilize the archive function in the fiddle.

Note: as of version 1.1.3 the filter behavior has changed. You'll now want to use

ng-repeat='todo in todos | filter:{done:true}'

Fiddle: http://jsfiddle.net/UdbVL/1/

Upvotes: 5

timactive
timactive

Reputation: 829

Ok,

update variable with only data checked

your model :

$scope.todos = [
        {text:'foo'        , done:false}, 
        {text:'foobar'     , done:true},
        {text:'foofoo'     , done:false}, 
        {text:'foobar2'    , done:true}
 ]

you want only checked :

$scope.todoselect = $filter('filter')($scope.todos, {done:true});

when model change you want to update your variable so use watch in controller

$scope.$watch('todos', function(newval, oldval){
                        if (oldval != newval)
                        {   
                      $scope.todoselect = $filter('filter')($scope.todos, {done: true});
                            }
                            },true
                        );
  });

Sample : http://plnkr.co/edit/PnABre?p=preview

Upvotes: 0

Related Questions