16

在我的控制器中,我可以调用:

$scope.games[0];

访问我的游戏数组中的第一项。有没有办法做到这一点,记住过滤器。

例如我有:

filter:search

重复一遍,我怎么能调用 $scope.list[0]; 等于第一个搜索结果?

这个已经回答了,谢谢。我使用 AngluarJs 为 Lagged.com 构建了一个很酷的小部件,在这里玩免费的在线游戏:https ://lagged.com/

4

3 回答 3

10

这可以通过将过滤器的依赖项注入控制器并在代码中调用它来完成

var filteredArray = filterDependency(arrayToFilter,args);

它返回一个新的过滤数组。由于您使用的是“过滤器”过滤器(它是一个名称为过滤器的过滤器),因此依赖注入应该是filterFilter. 您的控制器应如下所示:

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

于 2013-05-31T23:15:07.633 回答
3

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

于 2013-05-31T23:39:12.380 回答
0

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

于 2013-05-31T23:35:54.420 回答