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

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 concrete example:

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>

Controller:

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

I want to filter the second input to the subject with a grade 'C', but I don't want to bind the model to the grade; I want to bind it to the title of the subject that has grade 'C'.

Is this possible, and if so, how is it done?


Solution 1:

You can use the "filter" filter in your controller to get all the "C" grades. Getting the first element of the result array will give you the title of the subject that has grade "C".

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

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

The same with plain ES6:

$scope.gradeC = $scope.results.subjects.filter((subject) => subject.grade === 'C')[0]

Solution 2:

<div ng-repeat="subject in results.subjects | filter:{grade:'C'}">
    <input ng-model="subject.title" />
</div>

Solution 3:

Here is a modified JSBin with a working sample:

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

Here is what I did with filters in the input:

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