过滤器后的数组中的第一个AngularJS [英] AngularJS First in array after Filter

查看:25
本文介绍了过滤器后的数组中的第一个AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

$scope.games[0];

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

例如我有:

过滤器:搜索

再说一遍,我如何调用 $scope.list[0];等于第一个搜索结果?

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

解决方案

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

varfilteredArray = filterDependency(arrayToFilter,args);

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

var app = angular.module('myapp',[]);app.controller('ctrlParent',function($scope,filterFilter){varfilteredArray = [];$scope.list = ["abc","def","ghi","abcdefghi"];$scope.$watch('search',function(newValue){filteredArray = filterFilter($scope.list, newValue);//对第一个结果做一些事情console.log(filteredArray[0]);//第一个结果});});

我们正在做的是在输入模型(search)上设置一个监视,以便我们可以在输入更改时获取新值并重新过滤数组.

<小时>

还有:

如果您需要从视图中访问 ng-repeat 索引,您可以使用 ng-repeat<内的特殊属性 $index/code> 喜欢:

{{$index}}

您还可以使用 $first$middle$last 如本 Angular 文档所示.

演示:这是一个小提琴

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/

解决方案

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

这篇关于过滤器后的数组中的第一个AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆