2013-05-06 70 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