In Angular, I need to search objects in an array

后端 未结 7 1221
时光说笑
时光说笑 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 07:39

    A dirty and easy solution could look like

    $scope.showdetails = function(fish_id) {
        angular.forEach($scope.fish, function(fish, key) {
            fish.more = fish.id == fish_id;
        });
    };
    
    0 讨论(0)
  • 2020-12-04 07:42

    To add to @migontech's answer and also his address his comment that you could "probably make it more generic", here's a way to do it. The below will allow you to search by any property:

    .filter('getByProperty', function() {
        return function(propertyName, propertyValue, collection) {
            var i=0, len=collection.length;
            for (; i<len; i++) {
                if (collection[i][propertyName] == +propertyValue) {
                    return collection[i];
                }
            }
            return null;
        }
    });
    

    The call to filter would then become:

    var found = $filter('getByProperty')('id', fish_id, $scope.fish);
    

    Note, I removed the unary(+) operator to allow for string-based matches...

    0 讨论(0)
  • 2020-12-04 07:44

    Angularjs already has filter option to do this , https://docs.angularjs.org/api/ng/filter/filter

    0 讨论(0)
  • 2020-12-04 07:53

    Saw this thread but I wanted to search for IDs that did not match my search. Code to do that:

    found = $filter('filter')($scope.fish, {id: '!fish_id'}, false);
    
    0 讨论(0)
  • 2020-12-04 07:56

    You can use the existing $filter service. I updated the fiddle above http://jsfiddle.net/gbW8Z/12/

     $scope.showdetails = function(fish_id) {
         var found = $filter('filter')($scope.fish, {id: fish_id}, true);
         if (found.length) {
             $scope.selected = JSON.stringify(found[0]);
         } else {
             $scope.selected = 'Not found';
         }
     }
    

    Angular documentation is here http://docs.angularjs.org/api/ng.filter:filter

    0 讨论(0)
  • 2020-12-04 08:00

    Your solutions are correct but unnecessary complicated. You can use pure javascript filter function. This is your model:

         $scope.fishes = [{category:'freshwater', id:'1', name: 'trout', more:'false'},  {category:'freshwater', id:'2', name:'bass', more:'false'}];
    

    And this is your function:

         $scope.showdetails = function(fish_id){
             var found = $scope.fishes.filter({id : fish_id});
             return found;
         };
    

    You can also use expression:

         $scope.showdetails = function(fish_id){
             var found = $scope.fishes.filter(function(fish){ return fish.id === fish_id });
             return found;
         };
    

    More about this function: LINK

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