angularjs - 如何根据其属性之一的值在控制器中获取 ng-repeat 过滤器中项目的索引? [英] angularjs - how to get in the controller the index of an item in a ng-repeat filter based on the value of one of its properties?
问题描述
我在我的 html 文件中使用 ng-repeat 来显示过滤的项目:
I use a ng-repeat in my html file to display filtered items:
<li ng-repeat="item in (filteredItems = (items | filter:query))">
{{ item.name }}
</a>
在控制器中,我想根据他的一个属性获取项目的索引.
In the controller, I'd like to get the index of an item based on one of his property.
精确:我想在过滤列表中获取索引,而不是在整个列表中.
Precision: I'd like to get the index in the filtered list and not in the whole list.
例如,这里将是项目名称为 some_item_7
的索引.
Here for example, it will be the index of the item witch name is some_item_7
.
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope',
function MyCtrl($scope) {
$scope.query = 'some';
$scope.items =
[
{ name: 'some_item_1' },
{ name: 'another_item_2' },
{ name: 'some_item_3' },
{ name: 'another_item_4' },
{ name: 'some_item_5' },
{ name: 'another_item_6' },
{ name: 'some_item_7' },
{ name: 'another_item_8' },
{ name: 'some_item_9' }
];
$scope.itemNext = function (item) {
console.log(item.name);
};
$scope.getIndexFromName = function (name) {
console.log("trying to get the index of the item with name = " + name);
}
$scope.getIndexFromName('some_item_7');
}
]);
http://plnkr.co/edit/C8gL9qV1MyonTwDENO9L?p=preview
有什么想法吗?
推荐答案
您的 ng-repeat 表达式在您的作用域上创建了 FilteredList 数组.
Your ng-repeat expression creates the filteredList array on your scope.
<li ng-repeat="item in (filteredItems = (items | filter:query))">
您可以像任何数组一样遍历它,检查与 name 参数匹配的项目.$scope.filteredItems
You can loop through it like any array, checking for the item matching the name parameter.
$scope.filteredItems
这是一个演示:http://plnkr.co/69nnbaZaulgX0odG7g7Y
请参阅此相关帖子:AngularJS - 如何获得ngRepeat 过滤结果参考
更新
您的评论表明您不想等待 ng-repeat 创建过滤项数组.您可以使用 $filter 服务在页面之前轻松初始化相同的数组负载.使用:
Update
Your comments indicate that you don't want to wait for ng-repeat to create the array of filtered items. You can use the $filter service to easily initialize the same array before the page loads. Use:
$scope.filteredItems = $filter('filter')($scope.items, {name: $scope.query}, false)
这样做不会干扰 ng-repeat
在 DOM 创建期间将其过滤结果保存到相同的 filteredItems
数组.
Doing so does not interfere with ng-repeat
saving its filter results to the same filteredItems
array during DOM creation.
这是一个更新的(和交互式的)演示:http://plnkr.co/NSvBz1yWvmeFgXITutZF
Here is an updated (and interactive) demo: http://plnkr.co/NSvBz1yWvmeFgXITutZF
这篇关于angularjs - 如何根据其属性之一的值在控制器中获取 ng-repeat 过滤器中项目的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!