在 Angular 中,我需要在数组中搜索对象 [英] In Angular, I need to search objects in an array

查看:37
本文介绍了在 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.

这篇关于在 Angular 中,我需要在数组中搜索对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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