In Angular, I need to search objects in an array

后端 未结 7 1246
时光说笑
时光说笑 2020-12-04 07:30

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-resour

相关标签:
7条回答
  • 2020-12-04 08:01

    I know if that can help you a bit.

    Here is something I tried to simulate for you.

    Checkout the jsFiddle ;)

    http://jsfiddle.net/migontech/gbW8Z/5/

    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;
      }
    });
    

    Usage in controller:

    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.

    0 讨论(0)
提交回复
热议问题