How do I filter an array with AngularJS and use a property of the filtered object as the ng-model attribute?

前端 未结 8 1434
刺人心
刺人心 2020-11-30 19:17

If I have an array of objects, and I want to bind the Angular model to a property of one of the elements based on a filter, how do I do that? I can explain better with a con

8条回答
  •  清歌不尽
    2020-11-30 19:26

    if you wanted to create a separate list of results in the controller you could apply a filter

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

    Then you can reference failedSubjects the same way you would reference the results object

    you can read more about it here https://docs.angularjs.org/guide/filter

    since this answer angular have updated the documentation they now recommend calling the filter

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

提交回复
热议问题