问题描述
在我的控制器我可以打电话:
In my controller I can call:
$scope.list[0];
要访问我的数组中的第一项。有没有办法记住这样做保存过滤器。
To access the first item in my array. Is there a way to do this keeping Filters in mind.
例如我有:
filter:search
在我复读,我怎么能叫$ scope.list [0];等于第一个搜索结果?
On my repeat, how can I call $scope.list[0]; to equal the first search result?
推荐答案
这可以通过注入过滤器的依赖到控制器,把它在code像
This can be done by injecting the filter's dependency into a controller and calling it in code like
var filteredArray = filterDependency(arrayToFilter,args);
返回一个新的,过滤阵列。由于您使用的是过滤器过滤器(这是一个过滤器,其名称是过滤器),依赖注入应 filterFilter
。您的控制器应是这个样子:
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.
同时
如果您需要从视图中访问 NG-重复
的索引,您可以使用特殊属性 $指数
里面的 NG-重复
这样的:
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.
演示:
这篇关于AngularJs先在过滤后的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!