source

Angular를 사용하여 어레이를 필터링하려면 어떻게 해야 합니까?필터링된 객체의 속성을 ng-model 속성으로 사용하시겠습니까?

factcode 2023. 3. 5. 21:59
반응형

Angular를 사용하여 어레이를 필터링하려면 어떻게 해야 합니까?필터링된 객체의 속성을 ng-model 속성으로 사용하시겠습니까?

오브젝트 배열이 있고 필터에 기반한 요소 중 하나의 속성에 Angular 모델을 바인드하려면 어떻게 해야 합니까?구체적인 예를 들어 설명하겠습니다.

HTML:

<!DOCTYPE html>
<html ng-app>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
        <meta charset=utf-8 />
        <title>JS Bin</title>
    </head>
    <body ng-controller="MyCtrl">
        <input ng-model="results.year">
        <input ng-model="results.subjects.title | filter:{grade:'C'}">
    </body>
</html>

컨트롤러:

function MyCtrl($scope) {
  $scope.results = {
    year:2013,
    subjects:[
      {title:'English',grade:'A'},
      {title:'Maths',grade:'A'},
      {title:'Science',grade:'B'},
      {title:'Geography',grade:'C'}
    ]
  };
}

JSBin : http://jsbin.com/adisax/1/edit

과목에 대한 두 번째 입력을 C등급으로 필터링하고 싶지만 모델을 등급에 바인딩하고 싶지 않습니다. C등급을 받은 과목의 제목에 바인딩하고 싶습니다.

이것이 가능한가, 가능하다면 어떻게 해야 하는가?

컨트롤러의 "필터" 필터를 사용하여 모든 "C" 등급을 얻을 수 있습니다.결과 배열의 첫 번째 요소를 가져오면 "C" 등급을 받은 과목의 제목이 나타납니다.

$scope.gradeC = $filter('filter')($scope.results.subjects, {grade: 'C'})[0];

http://jsbin.com/ewitun/1/edit

플레인 ES6에서도 마찬가지:

$scope.gradeC = $scope.results.subjects.filter((subject) => subject.grade === 'C')[0]
<div ng-repeat="subject in results.subjects | filter:{grade:'C'}">
    <input ng-model="subject.title" />
</div>

다음으로 작업 샘플이 있는 수정된 JSBin을 나타냅니다.

http://jsbin.com/sezamuja/1/edit

입력된 필터에 대해 수행한 작업은 다음과 같습니다.

<input ng-model="(results.subjects | filter:{grade:'C'})[0].title">

$filter를 다음과 같이 사용하는 경우 주의하시기 바랍니다.

$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'});

아, 모르겠어요 CC나 AC, C+나 CCC 같은 다른 등급이 나왔죠정확한 일치를 위한 요건을 추가해야 합니다.

$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'}, true);

이렇게 커미션 세부사항을 보고 있자니 정말 죽었습니다.

var obj = this.$filter('filter')(this.CommissionTypes, { commission_type_id: 6}))[0];

커미션 ID가 6이 아닌 56이기 때문에 버그로 호출되었을 뿐입니다.

true를 추가하면 완전히 일치합니다.

var obj = this.$filter('filter')(this.CommissionTypes, { commission_type_id: 6}, true))[0];

그래도 저는 이것을 선호합니다(타이프 스크립트를 사용하므로 "Let"과 =>).

let obj = this.$filter('filter')(this.CommissionTypes, (item) =>{ 
             return item.commission_type_id === 6;
           })[0];

제가 그렇게 하는 이유는 앞으로 언젠가 필터링된 데이터에서 더 많은 정보를 얻고 싶기 때문입니다.그 안에 기능이 있어서 보닛을 열어놨어요.

컨트롤러에 별도의 결과 목록을 만들고 싶다면 필터를 적용할 수 있습니다.

function MyCtrl($scope, filterFilter) {
  $scope.results = {
    year:2013,
    subjects:[
      {title:'English',grade:'A'},
      {title:'Maths',grade:'A'},
      {title:'Science',grade:'B'},
      {title:'Geography',grade:'C'}
    ]
  };
  //create a filtered array of results 
  //with grade 'C' or subjects that have been failed
  $scope.failedSubjects = filterFilter($scope.results.subjects, {'grade':'C'});
}

그런 다음 결과 개체를 참조하는 것과 동일한 방법으로 failed Subjects를 참조할 수 있습니다.

자세한 것은, https://docs.angularjs.org/guide/filter 를 참조해 주세요.

이 답변 각도가 문서를 업데이트했으므로 이제 필터를 호출할 것을 권장합니다.

// update 
// eg: $filter('filter')(array, expression, comparator, anyPropertyKey);
// becomes
$scope.failedSubjects = $filter('filter')($scope.results.subjects, {'grade':'C'});

ES6를 사용하는 경우 다음 작업을 수행할 수 있습니다.

var sample = [1, 2, 3]

var result = sample.filter(elem => elem !== 2)

/* output */
[1, 3]

또한 필터는 기존 어레이를 업데이트하지 않고 필터링된 새 어레이를 매번 반환합니다.

또한 다음과 같은 기능을 사용할 수 있습니다.$filter('filter')

var foo = $filter('filter')($scope.results.subjects, function (item) {
  return item.grade !== 'A';
});

여러 열이 있는 HTML에서 동일한 필터를 적용하는 경우, 예를 들어 다음과 같습니다.

 variable = (array | filter : {Lookup1Id : subject.Lookup1Id, Lookup2Id : subject.Lookup2Id} : true)

언급URL : https://stackoverflow.com/questions/17945861/how-do-i-filter-an-array-with-angularjs-and-use-a-property-of-the-filtered-objec

반응형