AngularJS First in array after Filter

前端 未结 3 1721
时光取名叫无心
时光取名叫无心 2021-01-07 23:34

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

相关标签:
3条回答
  • 2021-01-07 23:57

    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

    0 讨论(0)
  • 2021-01-08 00:06

    Are you using "ng-repeat"? If so take a look at the properties $first, $index, $middle, and $last. This will allow you to get info on the specific item from the repeat.

    For more info check here: http://docs.angularjs.org/api/ng.directive:ngRepeat

    0 讨论(0)
  • 2021-01-08 00:17

    Not with bracket access. If you have an ng-repeat with a filter:

    ng-repeat="thing in things | filter:search"
    

    The filtered list here is kind of anonymous - it doesn't have a name that you can access.

    That said, if you take a look at the docs for ngRepeat, you'll see that inside each repeater's scope, you have access to $index, $first, $middle, and $last.

    So something like

    <body ng-app="App" ng-controller="Main">
        <pre ng-repeat="n in nums | filter:isOdd">
            n={{n}}:index={{$index}}:first={{$first}}:middle{{$middle}}:last={{$last}}
        </pre>
    </body>
    

    Would yield:

        n=1:index=0:first=true:middlefalse:last=false
    
        n=3:index=1:first=false:middletrue:last=false
    
        n=5:index=2:first=false:middlefalse:last=true
    

    Fiddle

    0 讨论(0)
提交回复
热议问题