Saturday, May 25, 2024
 Popular · Latest · Hot · Upcoming
49
rated 0 times [  53] [ 4]  / answers: 1 / hits: 34616  / 11 Years ago, fri, may 31, 2013, 12:00:00

In my controller I can call:



$scope.games[0];


To access the first item in my games array. Is there a way to do this keeping Filters in mind.



For example I have:



filter:search


On my repeat, how can I call $scope.list[0]; to equal the first search result?



This has been answered, thank you. I built a cool widget using AngluarJs for Lagged.com, play free online games here: https://lagged.com/


More From » angularjs

 Answers
35

This can be done by injecting the filter's dependency into a controller and calling it in code like



var filteredArray = filterDependency(arrayToFilter,args);


which returns a new, filtered array. Since you are using the filter filter (it's a filter whose name is filter), the dependency injection should be filterFilter. Your controller should look something like this:



var app = angular.module('myapp',[]);
app.controller('ctrlParent',function($scope,filterFilter){
var filteredArray = [];
$scope.list = [abc,def,ghi,abcdefghi];
$scope.$watch('search',function(newValue){
filteredArray = filterFilter($scope.list, newValue);
// do something with the first result
console.log(filteredArray[0]); // first result
});
});


What we're doing is setting a watch on the input model (search) so we can get the new value and re-filter the array any time the input is changed.






Also:



If you need to access the ng-repeat index from within the view, you can use the special property $index inside of the ng-repeat like:



<div ng-repeat=item in list | filter:search>
{{$index}}
</div>


You can also use $first, $middle, and $last as shown in this Angular doc.



Demo: Here is a fiddle


[#77882] Thursday, May 30, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elliem

Total Points: 415
Total Questions: 117
Total Answers: 94

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
;