如何在AngularJS中创建过滤器

时间:2013-05-06 17:08:37

标签: angularjs angularjs-filter

使用AngularJS,如何在数组中创建项的子集?

例如;从“todos”创建一个新数组,该数组仅包含“done:true”项。

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

见约10:45 - >端

2 个答案:

答案 0 :(得分:5)

只需将过滤器添加到ngRepeat并仅显示您想要的内容:

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

小提琴:http://jsfiddle.net/dPWsv/1/

如果要从列表中完全删除元素,请使用小提琴中的archive函数。

注意:从版本1.1.3开始,过滤器行为已更改。你现在想要使用

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

小提琴:http://jsfiddle.net/UdbVL/1/

答案 1 :(得分:0)

好的,

仅使用数据检查更新变量

你的模特:

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

您只想检查:

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

当模型更改时,您想要更新变量,因此请在控制器中使用watch

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

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