在 Angular 中,我需要在数组中搜索对象
在 Angular 中,我有一个返回大量对象的对象.每个都有一个 ID(它存储在一个平面文件中,因此没有数据库,而且我似乎无法使用 ng-resource
)
In Angular, I have in scope a object which returns lots of objects. Each has an ID (this is stored in a flat file so no DB, and I seem to not be able to user ng-resource
)
在我的控制器中:
$scope.fish = [
{category:'freshwater', id:'1', name: 'trout', more:'false'},
{category:'freshwater', id:'2', name:'bass', more:'false'}
];
在我看来,我有关于默认情况下使用 ng-show
more 隐藏的鱼的其他信息,但是当我单击简单的 show more 选项卡时,我想调用函数 显示细节(fish.fish_id)
.我的函数看起来像:
In my view I have additional information about the fish hidden by default with the ng-show
more, but when I click the simple show more tab, I would like to call the function showdetails(fish.fish_id)
.
My function would look something like:
$scope.showdetails = function(fish_id) {
var fish = $scope.fish.get({id: fish_id});
fish.more = true;
}
现在在视图中会显示更多详细信息.但是,在搜索完文档后,我不知道如何搜索 fish
数组.
Now in the the view the more details shows up. However after searching through the documentation I can't figure out how to search that fish
array.
那么如何查询数组呢?在控制台中,我如何调用调试器以便我可以使用 $scope
对象?
So how do I query the array? And in console how do I call debugger so that I have the $scope
object to play with?
我知道这是否对您有所帮助.
I know if that can help you a bit.
这是我试图为你模拟的东西.
Here is something I tried to simulate for you.
检查 jsFiddle ;)
Checkout the jsFiddle ;)
http://jsfiddle.net/migontech/gbW8Z/5/
创建了一个您也可以在ng-repeat"中使用的过滤器
Created a filter that you also can use in 'ng-repeat'
app.filter('getById', function() {
return function(input, id) {
var i=0, len=input.length;
for (; i<len; i++) {
if (+input[i].id == +id) {
return input[i];
}
}
return null;
}
});
在控制器中的使用:
app.controller('SomeController', ['$scope', '$filter', function($scope, $filter) {
$scope.fish = [{category:'freshwater', id:'1', name: 'trout', more:'false'}, {category:'freshwater', id:'2', name:'bass', more:'false'}]
$scope.showdetails = function(fish_id){
var found = $filter('getById')($scope.fish, fish_id);
console.log(found);
$scope.selected = JSON.stringify(found);
}
}]);
如果有任何问题,请告诉我.
If there are any questions just let me know.