2013-05-06 72 views
2

使用AngularJS的过滤器,你如何在一个数组创建项目的一个子集?如何创建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 - >结束

+0

好了,我在http://stackoverflow.com/questions/16394055/checkbox-list-breaks-why-and-optimal创建示例-angularjs路/ 16395257#16395257。 – timactive 2013-05-06 17:13:26

回答

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/

+0

我最终得到了这个工作。感谢您的帮助。 https://github.com/spudstud/angular-todo – spuder 2013-05-06 20:44:40

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}); 

当模型变化要更新您的变量,以便使用手表控制器

$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