Programing

Angular에서는 배열에서 객체를 검색해야합니다.

lottogame 2020. 7. 22. 21:30
반응형

Angular에서는 배열에서 객체를 검색해야합니다.


Angular에서는 많은 객체를 반환하는 객체가 있습니다. 각각 ID가 있습니다 (이것은 플랫 파일에 저장되므로 DB가 없으므로 사용자가 사용할 수없는 것 같습니다 ng-resource)

내 컨트롤러에서 :

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

내보기에는 기본적으로 ng-show더 많은 물고기가 숨겨져 있다는 추가 정보가 있지만 간단한 더보기 탭을 클릭하면 함수를 호출하고 싶습니다 showdetails(fish.fish_id). 내 기능은 다음과 같습니다.

$scope.showdetails = function(fish_id) {  
    var fish = $scope.fish.get({id: fish_id});
    fish.more = true;
}

이제 뷰에 자세한 내용이 표시됩니다. 그러나 설명서를 검색 한 후 해당 fish배열 을 검색하는 방법을 알 수 없습니다 .

그렇다면 어떻게 배열을 쿼리합니까? 콘솔 $scope에서 재생할 객체를 갖도록 디버거를 어떻게 호출 합니까?


나는 그것이 당신을 조금 도울 수 있는지 알고 있습니다.

여기 내가 당신을 위해 시뮬레이션하려고했습니다.

jsFiddle을 확인하십시오.)

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

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

질문이 있으면 알려주세요.


기존 $ filter 서비스를 사용할 수 있습니다. 위의 바이올린을 업데이트했습니다 : 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';
     }
 }

각도 문서는 여기 http://docs.angularjs.org/api/ng.filter:filter


@migontech의 답변과 그의 대답에 추가하여 "아마도 더 일반적으로 만들 수있다"는 의견을 제시하려면 다음과 같이하십시오. 아래는 어떤 속성 으로든 검색 할 수 있도록합니다.

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

그러면 필터 호출이 다음과 같이됩니다.

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

문자열 기반 일치를 허용하기 위해 단항 (+) 연산자를 제거했습니다 ...


더럽고 쉬운 솔루션은 다음과 같습니다.

$scope.showdetails = function(fish_id) {
    angular.forEach($scope.fish, function(fish, key) {
        fish.more = fish.id == fish_id;
    });
};

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


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


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

참고URL : https://stackoverflow.com/questions/15610501/in-angular-i-need-to-search-objects-in-an-array

반응형